From 4bba59193b73b9b2ed30fae9b8039844d8d49ee0 Mon Sep 17 00:00:00 2001 From: kt Date: Mon, 11 Nov 2024 10:55:58 -0700 Subject: [PATCH] golangci enable additional linters (prealloc predeclared whitespace tagalign) and fix issues (#27959) * golangci enable prealloc and predeclared linters and update config to go 1.22 * make whitespace & enable linter to see if it is still super slow * fix linting * tagalign * try out nakedret * make generate * fix potential crash --- .golangci.yml | 81 +++++++++++-------- GNUmakefile | 4 + internal/acceptance/data.go | 24 +++--- internal/clients/auth.go | 7 +- internal/clients/builder.go | 2 +- internal/clients/client_gen.go | 1 - internal/clients/graph/client.go | 3 +- internal/provider/provider.go | 1 - internal/sdk/frameworkhelpers/list.go | 1 - internal/sdk/resource_decode.go | 1 - internal/sdk/resource_encode.go | 1 - internal/sdk/resource_encode_test.go | 20 ++--- internal/sdk/resource_test.go | 2 +- .../aadb2c/aadb2c_directory_resource.go | 5 +- .../advisor_recommendations_data_source.go | 2 +- ...anagement_api_operation_policy_resource.go | 3 +- .../api_management_api_policy_resource.go | 3 +- .../api_management_api_resource.go | 5 +- ...api_management_api_version_set_resource.go | 13 +-- .../api_management_backend_resource.go | 5 +- .../api_management_logger_resource.go | 4 +- .../api_management_named_value_resource.go | 3 +- .../api_management_policy_resource.go | 3 +- .../api_management_product_policy_resource.go | 3 +- .../apimanagement/api_management_resource.go | 58 ++++++------- .../app_configuration_feature_resource.go | 5 +- .../app_configuration_key_resource.go | 3 +- .../app_configuration_resource.go | 1 - .../appconfiguration/feature_structs.go | 8 +- .../parse/app_configuration_key.go | 1 - .../application_insights_resource.go | 1 - ..._insights_smart_detection_rule_resource.go | 1 - ...ion_insights_workbook_template_resource.go | 6 +- .../app_service_environment_v3_data_source.go | 1 - .../app_service_environment_v3_resource.go | 9 ++- ...function_app_hybrid_connection_resource.go | 1 - .../services/appservice/helpers/app_stack.go | 3 - .../appservice/helpers/auth_v2_schema.go | 2 - .../helpers/common_web_app_schema.go | 9 ++- .../services/appservice/helpers/fx_strings.go | 1 - .../appservice/helpers/shared_schema.go | 2 +- .../appservice/helpers/web_app_slot_schema.go | 4 - .../helpers/windows_web_app_schema.go | 3 - .../appservice/linux_function_app_resource.go | 3 - .../linux_function_app_slot_resource.go | 1 - ..._function_app_slot_resource_authv2_test.go | 1 - .../appservice/linux_web_app_data_source.go | 1 - .../appservice/linux_web_app_slot_resource.go | 1 - ...linux_web_app_slot_resource_authv2_test.go | 1 - .../appservice/source_control_resource.go | 1 - .../appservice/validate/static_web_app.go | 17 ++-- .../windows_function_app_resource.go | 4 - .../windows_function_app_slot_resource.go | 1 - .../appservice/windows_web_app_data_source.go | 1 - .../appservice/windows_web_app_resource.go | 1 - .../windows_web_app_slot_resource.go | 1 - ...c_kubernetes_cluster_extension_resource.go | 1 - .../stored_attestation_policy_base64.go | 13 +-- .../parse/id_scopedroleassignment.go | 2 +- .../authorization/parse/role_assignment.go | 17 ++-- .../parse/role_assignment_test.go | 1 - .../authorization/role_assignment_resource.go | 1 - .../authorization/role_management_policy.go | 1 - .../role_management_policy_data_source.go | 1 - .../role_management_policy_resource.go | 1 - ...anage_configuration_assignment_resource.go | 2 +- .../automation_account_resource_test.go | 3 - ...n_connection_service_principal_resource.go | 1 - .../automation_connection_type_resource.go | 8 +- .../automation/automation_runbook_resource.go | 32 +++----- .../automation_schedule_resource.go | 2 - ..._software_update_configuration_resource.go | 1 - .../automation/automation_webhook_resource.go | 1 - .../helper/automation_job_schedule.go | 2 +- ..._hci_marketplace_gallery_image_resource.go | 1 - .../services/batch/batch_account_resource.go | 2 - internal/services/batch/batch_pool.go | 13 ++- internal/services/batch/client/client.go | 2 +- .../blueprint_assignment_resource.go | 3 +- .../blueprints/blueprint_assingment.go | 7 +- .../services/bot/bot_connection_resource.go | 15 ++-- internal/services/bot/validate/bot.go | 8 +- .../cdn/cdn_frontdoor_route_resource.go | 5 +- internal/services/cdn/validate/cdn.go | 6 +- .../services/chaosstudio/client/client_gen.go | 1 - .../chaos_studio_experiment_poller.go | 1 - .../cognitive/ai_services_resource.go | 3 +- internal/services/cognitive/client/client.go | 1 - .../cognitive_deployment_resource.go | 1 - .../email_service_domain_resource.go | 1 - .../compute/disk_encryption_set_resource.go | 1 - .../services/compute/image_resource_test.go | 1 - .../compute/linux_virtual_machine_resource.go | 1 - ...l_machine_scale_set_resource_other_test.go | 1 - .../services/compute/managed_disk_resource.go | 1 - .../orchestrated_virtual_machine_scale_set.go | 4 - ...d_virtual_machine_scale_set_data_source.go | 1 - ...virtual_machine_scale_set_resource_test.go | 1 - .../compute/shared_image_data_source.go | 1 - .../compute/shared_image_version_resource.go | 2 - .../shared_image_versions_data_source.go | 1 - .../virtual_machine_run_command_resource.go | 2 - ...dows_virtual_machine_scale_set_resource.go | 1 - ...l_machine_scale_set_resource_other_test.go | 1 - ..._app_environment_custom_domain_resource.go | 1 - ...container_app_environment_resource_test.go | 2 - ...r_app_environment_storage_resource_test.go | 1 - .../containerapps/container_app_resource.go | 2 - .../containerapps/helpers/container_apps.go | 1 - .../services/containers/client/client_gen.go | 1 - .../containers/container_group_resource.go | 33 ++++---- .../container_registry_agent_pool_resource.go | 1 - .../containers/container_registry_resource.go | 1 - .../container_registry_resource_test.go | 1 - .../container_registry_task_resource.go | 1 - .../kubernetes_cluster_data_source.go | 1 - .../kubernetes_cluster_other_resource_test.go | 2 - .../containers/kubernetes_cluster_resource.go | 5 -- ...ubernetes_cluster_scaling_resource_test.go | 1 - ...rusted_access_role_binding_resource_gen.go | 4 - .../kubernetes_fleet_member_resource_gen.go | 4 - .../kubernetes_fleet_update_run_resource.go | 1 - ...bernetes_fleet_update_strategy_resource.go | 1 - .../services/cosmos/common/indexing_policy.go | 6 +- .../cosmos/cosmosdb_account_resource.go | 4 +- .../cosmos/cosmosdb_gremlin_graph_resource.go | 1 - ...cosmosdb_mongo_role_definition_resource.go | 14 ++-- .../cosmosdb_postgresql_cluster_resource.go | 5 +- .../cosmos/cosmosdb_sql_container_resource.go | 1 - ..._managed_private_endpoint_resource_test.go | 1 - .../dashboard/dashboard_grafana_resource.go | 10 +-- .../migration/device_edge_order_v0_to_v1.go | 5 +- ...atabricks_customer_managed_key_resource.go | 1 - .../databricks_workspace_resource.go | 1 - .../datafactory/azuresdkhacks/pipelines.go | 20 ++--- internal/services/datafactory/data_factory.go | 4 +- ...ctory_managed_private_endpoint_resource.go | 1 - ...ta_factory_trigger_schedule_data_source.go | 1 - ...actory_trigger_tumbling_window_resource.go | 2 +- ..._share_dataset_blob_storage_data_source.go | 1 - ...ata_share_dataset_blob_storage_resource.go | 1 - .../services/devcenter/client/client_gen.go | 1 - .../devcenter/dev_center_resource_gen.go | 3 - .../devtestlabs/dev_test_lab_data_source.go | 1 - .../dynatrace/dynatrace_monitors_resource.go | 3 +- .../elastic_san_volume_group_resource.go | 2 +- .../services/eventhub/eventhub_resource.go | 1 - .../validate/eventhub_message_retention.go | 8 +- .../eventhub/validate/eventhub_partition.go | 8 +- ...ll_application_rule_collection_resource.go | 1 - .../firewall_nat_rule_collection_resource.go | 1 - ...rewall_network_rule_collection_resource.go | 1 - .../firewall/firewall_policy_resource.go | 26 +++--- .../fluidrelay/validate/server_name.go | 7 +- internal/services/frontdoor/customizediff.go | 15 ++-- .../services/graphservices/client/client.go | 1 - .../hdinsight_kafka_cluster_resource.go | 1 - .../healthcare_dicom_data_source.go | 1 - .../healthcare/healthcare_fhir_resource.go | 2 - ...dtech_service_fhir_destination_resource.go | 1 - .../healthcare/healthcare_service_resource.go | 1 - .../hybridcompute/arc_machine_data_source.go | 4 +- .../arc_machine_extension_resource.go | 2 - internal/services/iotcentral/client/client.go | 3 +- .../services/kusto/kusto_cluster_resource.go | 1 - ...virtual_machine_scale_set_resource_test.go | 1 - .../lighthouse_definition_resource.go | 12 +-- .../backend_address_pool_data_source.go | 1 - .../loadbalancer/loadbalancer_data_source.go | 1 - .../services/loadtestservice/client/client.go | 1 - .../loadtestservice/load_test_resource.go | 4 - .../log_analytics_data_export_resource.go | 17 ++-- .../log_analytics_solution_resource.go | 1 - .../logic/integration_service_environment.go | 2 +- ..._integration_account_agreement_resource.go | 1 - ...p_integration_account_assembly_resource.go | 1 - ...ntegration_account_certificate_resource.go | 1 - .../logic/logic_app_workflow_resource.go | 2 +- ...ance_assignment_dedicated_host_resource.go | 3 +- ...nance_assignment_dynamic_scope_resource.go | 2 - ...nce_assignment_virtual_machine_resource.go | 3 +- .../maintenance_configuration_resource.go | 13 +-- ..._maintenance_configurations_data_source.go | 5 +- .../managed_application_resource.go | 3 +- ...ity_module_key_rotation_policy_resource.go | 1 - ...naged_hardware_security_module_resource.go | 12 +-- ...ecurity_module_role_assignment_resource.go | 4 +- ...ecurity_module_role_definition_resource.go | 4 +- .../managedidentity/client/client_gen.go | 1 - .../user_assigned_identity_resource_gen.go | 1 - .../management_group_resource_test.go | 2 +- .../subscription_association_resource_test.go | 2 +- .../mobile_network_service_data_source.go | 3 +- .../mobile_network_service_resource.go | 12 +-- .../mobile_network_sim_policy_data_source.go | 1 - .../mobile_network_sim_policy_resource.go | 9 +-- .../services/mongocluster/client/client.go | 1 - .../monitor/monitor_action_group_resource.go | 1 - .../monitor_autoscale_setting_resource.go | 4 - .../monitor/monitor_metric_alert_resource.go | 1 - .../monitor_private_link_scope_resource.go | 1 - ...scheduled_query_rules_alert_data_source.go | 1 - ...scheduled_query_rules_alert_v2_resource.go | 21 ++--- .../mssql/mssql_failover_group_resource.go | 4 +- ...er_transparent_data_encryption_resource.go | 1 - ...ne_availability_group_listener_resource.go | 6 -- ...ailability_group_listener_resource_test.go | 1 - .../mssql_virtual_machine_group_resource.go | 3 - .../mssqlmanagedinstance/client/client.go | 1 - .../mssql_managed_database_resource.go | 1 - ...active_directory_administrator_resource.go | 2 - .../mssql_managed_instance_data_source.go | 1 - .../mssql_managed_instance_resource.go | 1 - ...instance_security_alert_policy_resource.go | 1 - ...ce_transparent_data_encryption_resource.go | 2 - .../netapp_account_encryption_data_source.go | 3 - .../netapp_account_encryption_resource.go | 3 - .../netapp/netapp_account_resource.go | 1 - ...etapp_volume_group_sap_hana_data_source.go | 1 - .../netapp_volume_group_sap_hana_resource.go | 8 -- .../services/netapp/netapp_volume_helper.go | 2 - .../netapp_volume_quota_rule_data_source.go | 1 - .../netapp_volume_quota_rule_resource.go | 2 - ...olume_group_sap_hana_volumes_validation.go | 6 -- .../volume_quota_rule_quota_validations.go | 2 - .../network/custom_ip_prefix_resource.go | 1 - ...ss_route_circuit_authorization_resource.go | 1 - ...press_route_circuit_connection_resource.go | 1 - .../express_route_circuit_peering_resource.go | 1 - .../network/express_route_circuit_resource.go | 1 - .../network/express_route_gateway_resource.go | 1 - ...ecurity_group_association_resource_test.go | 1 - ..._manager_admin_rule_collection_resource.go | 4 +- .../network_manager_admin_rule_resource.go | 6 +- ...ger_connectivity_configuration_resource.go | 11 ++- .../network/network_manager_resource.go | 4 +- ...r_security_admin_configuration_resource.go | 6 +- ...ation_gateway_backend_address_pool_test.go | 2 - .../point_to_site_vpn_gateway_resource.go | 1 - ...private_endpoint_connection_data_source.go | 1 - .../network/public_ip_prefix_resource.go | 1 - .../services/network/route_map_resource.go | 24 +++--- .../services/network/route_server_resource.go | 1 - internal/services/network/subnet_resource.go | 2 +- .../services/network/virtual_hub_resource.go | 1 - .../virtual_hub_route_table_route_resource.go | 1 - .../virtual_hub_routing_intent_resource.go | 4 +- .../network/virtual_network_data_source.go | 2 - .../virtual_network_gateway_resource.go | 37 ++++----- .../services/network/vpn_gateway_resource.go | 1 - ...eb_application_firewall_policy_resource.go | 4 +- ...work_function_collector_policy_resource.go | 7 +- .../newrelic/new_relic_tag_rule_resource.go | 2 +- .../nginx/nginx_certificate_resource.go | 9 +-- .../nginx/nginx_configuration_resource.go | 23 +++--- .../nginx/nginx_deployment_resource.go | 26 +++--- .../autonomous_database_regular_resource.go | 3 +- .../oracle/cloud_vm_cluster_resource.go | 1 - .../oracle/exadata_infrastructure_resource.go | 7 +- .../validate/autonomous_database_regular.go | 57 +++++-------- internal/services/orbital/helper.go | 26 +++--- ...on_firewall_vhub_panorama_resource_test.go | 2 - ...on_firewall_vnet_panorama_resource_test.go | 3 - .../paloalto/schema/network_profile.go | 1 - internal/services/policy/assignment.go | 1 - .../policy/assignment_resource_base.go | 6 +- internal/services/policy/parse/scope.go | 3 +- ...ne_configuration_assignment_data_source.go | 1 - .../postgresql_flexible_server_resource.go | 1 - .../validate/flexible_server_storage_tier.go | 1 - ...esolver_dns_forwarding_ruleset_resource.go | 6 +- ...e_dns_resolver_forwarding_rule_resource.go | 6 +- ..._dns_resolver_inbound_endpoint_resource.go | 6 +- .../recoveryservices/azuresdkhacks/client.go | 4 +- .../recovery_services_vault_resource.go | 2 - ...very_hyperv_replication_policy_resource.go | 1 - .../site_recovery_replicated_vm_resource.go | 58 ++++++------- ...te_recovery_replicated_vm_resource_test.go | 1 - ...very_replication_recovery_plan_resource.go | 2 - ...replication_recovery_plan_resource_test.go | 1 - ...replication_policy_association_resource.go | 1 - ...very_vmware_replication_policy_resource.go | 1 - .../redis/redis_cache_resource_test.go | 1 - ...rise_cluster_location_flash_sku_support.go | 5 +- ...nterprise_cluster_location_zone_support.go | 5 +- .../resource/parse/resource_provider.go | 5 +- .../resource_deployment_script_common.go | 6 +- .../resource/resource_group_resource.go | 1 - .../search/search_service_resource.go | 3 +- ...nerability_assessments_setting_resource.go | 1 - ...ty_center_subscription_pricing_resource.go | 3 +- .../services/sentinel/sentinel_alert_rule.go | 25 +++--- .../sentinel/sentinel_alert_rule_anomaly.go | 1 - ...alytics_workspace_onboard_resource_test.go | 1 - ..._threat_intelligence_indicator_resource.go | 7 +- .../sentinel/sentinel_watchlist_resource.go | 1 - .../servicebus_namespace_resource.go | 1 - .../servicebus_subscription_resource.go | 2 - ...alr_service_custom_domain_resource_test.go | 1 - .../web_pubsub_custom_certificate_resource.go | 1 - .../web_pubsub_custom_domain_resource_test.go | 1 - ...ication_performance_monitoring_resource.go | 1 - ...ng_cloud_configuration_service_resource.go | 1 - internal/services/storage/blobs.go | 17 ++-- .../storage/migration/account_v3_to_v4.go | 1 - .../storage/parse/storage_table_entities.go | 2 +- .../storage_account_local_user_resource.go | 14 ++-- .../storage/storage_account_resource.go | 5 +- .../storage/storage_containers_data_source.go | 2 +- .../storage/storage_queue_data_source.go | 1 - .../storage/storage_share_resource_test.go | 1 - .../storage/storage_table_data_source.go | 6 +- internal/services/storagecache/hpc_cache.go | 2 +- .../storagecache/hpc_cache_resource.go | 5 +- .../storage_mover_source_endpoint_resource.go | 1 - .../validate/subscription_name.go | 9 ++- internal/services/synapse/client/client.go | 9 ++- ...virtual_machine_manager_server_resource.go | 1 - .../traffic_manager_profile_resource.go | 5 +- .../services/voiceservices/client/client.go | 1 - ...ervices_communications_gateway_resource.go | 2 +- ...p_single_node_virtual_instance_resource.go | 3 +- ...ap_three_tier_virtual_instance_resource.go | 5 +- .../check/check_possible_value.go | 2 +- .../document-lint/check/check_resource_all.go | 1 - .../document-lint/check/crossproperty.go | 12 +-- .../document-lint/check/document_fixer.go | 4 +- internal/tools/document-lint/md/normalize.go | 3 +- .../tools/document-lint/md/parse_md_test.go | 1 - .../tools/document-lint/md/resource_doc.go | 2 +- .../tools/document-lint/util/string_test.go | 1 - internal/tools/generator-resource-id/main.go | 1 - internal/tools/generator-services/main.go | 11 +-- .../rules/typed_sdk_bit_check.go | 1 - internal/tools/update-api-version/main.go | 2 +- 335 files changed, 636 insertions(+), 935 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7df2440e972a..6629896e8d64 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,7 +3,7 @@ run: timeout: 60m - go: 1.21 + go: 1.22 modules-download-mode: vendor skip-dirs: - /sdk/ # Excluding sdk folders as these are externally generated @@ -18,43 +18,50 @@ linters: disable-all: true enable: - asasalint # check for pass []any as any in variadic func(...any) - - asciicheck # code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - - decorder # Check declaration order and count of types, constants, variables and functions. - - durationcheck # Check for common mistakes when working with time.Duration - - dupword #Check for duplicated words in comments + - asciicheck # ensure code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - decorder # check declaration order and count of types, constants, variables and functions. + - durationcheck # check for common mistakes when working with time.Duration + - dupword # check for duplicated words in comments - errcheck # checking for unchecked errors - - gocritic # Linter for Go source code that specializes in simplifying code - - gofmt # Gofmt checks whether code was gofmt-ed + - gocritic # linter for Go source code that specializes in simplifying code + - gofmt # checks whether code was gofmt-ed #- gofumpt # Gofumpt is a stricter gofmt - - goimports # Check import statements are formatted according to the 'goimport' command - - gosimple # Linter for Go source code that specializes in simplifying code. - #- gosec # Gosec is a security linter for Go source code + - goimports # check import statements are formatted according to the 'goimport' command + - gosimple # linter for Go source code that specializes in simplifying code. - govet # reports suspicious constructs. It is roughly the same as 'go vet' (replaced vet and vetshadow) - - ineffassign # Detects when assignments to existing variables are not used - - misspell # Finds commonly misspelled English words. - #- nakedret # Checks that functions with naked returns are not longer than a maximum size + - ineffassign # detects when assignments to existing variables are not used + - misspell # finds commonly misspelled English words. #- nilerr # Finds the code that returns nil even if it checks that the error is not nil. #- nlreturn # Nlreturn checks for a new line before return and branch statements to increase code clarity. - #- paralleltest # Detects missing usage of t.Parallel() method in your Go test. - #- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. - #- prealloc # Finds slice declarations that could potentially be pre-allocated. - #- predeclared # Find code that shadows one of Go's predeclared identifiers. - - reassign # Checks that package variables are not reassigned. + #- paralleltest # detects missing usage of t.Parallel() method in your Go test. + - prealloc # finds slice declarations that could potentially be pre-allocated. + - predeclared # find code that shadows one of Go's predeclared identifiers. + - reassign # checks that package variables are not reassigned. #- revive #Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. - - staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. #- tparallel # Tparallel detects inappropriate usage of t.Parallel() method in your Go test codes. - - typecheck # doesn't exist?!>?! XXXXXXXXX - - unused # Checks Go code for unused constants, variables, functions and types. - - unconvert # Remove unnecessary type conversions. - - unparam # Reports unused function parameters. - - wastedassign # Finds wasted assignment statements - #- wsl Add or remove empty lines. + - tagalign # checks struct tags that do not align with the specified column in struct definitions. + - staticcheck # checks rules from staticcheck. It's not the same thing as the staticcheck binary. + - unused # checks Go code for unused constants, variables, functions and types. + - unconvert # checks for unnecessary type conversions. + - unparam # reports unused function parameters. + - wastedassign # finds wasted assignment statements + - whitespace # checks for unnecessary newlines at the start and end of functions, if, for, etc. ( + #- wsl # add or remove empty lines. + + ###### DISABLED because : integer overflow conversion int -> int32 + # - gosec # Gosec is a security linter for Go source code + + ##### DISABLED as i was fixing them with other linters, and not realizing how many there are - disabling for now even thou it is valid + #- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. + + #### VALID but DISABLED as we have a lot of these in the codebase to switch over + #- nakedret # Checks that functions with naked returns are not longer than a maximum size #### DISABLED TO DO IN ITS OWN PR - should be enabled and done ##### #- tenv #detects using os.Setenv instead of t.Setenv since Go1.17. - #### REQUIRES GO 1.22 ##### + #### bunch of hits, need to confirm if errors or not ##### #- copyloopvar #Detects range loop variables that are overwritten in the loop body #### DISABLED till %+v -> %w ##### @@ -64,12 +71,9 @@ linters: # disabled as it may be useful but there are a lot of switch statements in the codebase with unhandled inputs #- exhaustive #Check for missing cases in select statements - ###### DISABLED because golang will put the space back into //nolint: linter ###### + ###### DISABLED because golang will put the space back into `//nolint: linter` -> `// nolint: linter` ###### #- nolintlint #Reports ill-formed or insufficient nolint directives. - # Disabled for performance reasons - Ignores cache and takes 12+ minutes to run on the repo for _any_ change - #- whitespace #checks for unnecessary newlines at the start and end of functions, if, for, etc. - linters-settings: errcheck: ignore: github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema:ForceNew|Set,fmt:.*,io:Close @@ -78,4 +82,17 @@ linters-settings: - hdinsight - exportfs nakedret: - max-func-lines: 40 + max-func-lines: 30 + tagalign: + sort: true + order: + - json + - tfschema + - computed + predeclared: + ignore: new,min,max # should we use newer, minimum, and maximum instead? + revive: + rules: + - name: var-naming + disabled: true + diff --git a/GNUmakefile b/GNUmakefile index 66c3fb85195a..903b961ffbb8 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -80,6 +80,10 @@ whitespace: @echo "==> Fixing source code with whitespace linter..." golangci-lint run ./... --no-config --disable-all --enable=whitespace --fix +golangci-fix: + @echo "==> Fixing source code with all golangci linters..." + golangci-lint run ./... --fix + test: fmtcheck @TEST=$(TEST) ./scripts/run-gradually-deprecated.sh @TEST=$(TEST) ./scripts/run-test.sh diff --git a/internal/acceptance/data.go b/internal/acceptance/data.go index f2e4bc32b486..0c5ca55ffcdb 100644 --- a/internal/acceptance/data.go +++ b/internal/acceptance/data.go @@ -89,41 +89,41 @@ func BuildTestData(t *testing.T, resourceType string, resourceLabel string) Test } // RandomIntOfLength is a random 8 to 18 digit integer which is unique to this test case -func (td *TestData) RandomIntOfLength(len int) int { - // len should not be +func (td *TestData) RandomIntOfLength(length int) int { + // length should not be // - greater then 18, longest a int can represent // - less then 8, as that gives us YYMMDDRR - if 8 > len || len > 18 { - panic("Invalid Test: RandomIntOfLength: len is not between 8 or 18 inclusive") + if 8 > length || length > 18 { + panic("Invalid Test: RandomIntOfLength: length is not between 8 or 18 inclusive") } // 18 - just return the int - if len >= 18 { + if length >= 18 { return td.RandomInteger } // 16-17 just strip off the last 1-2 digits - if len >= 16 { - return td.RandomInteger / int(math.Pow10(18-len)) + if length >= 16 { + return td.RandomInteger / int(math.Pow10(18-length)) } - // 8-15 keep len - 2 digits and add 2 characters of randomness on + // 8-15 keep length - 2 digits and add 2 characters of randomness on s := strconv.Itoa(td.RandomInteger) r := s[16:18] - v := s[0 : len-2] + v := s[0 : length-2] i, _ := strconv.Atoi(v + r) return i } // RandomStringOfLength is a random 1 to 1024 character string which is unique to this test case -func (td *TestData) RandomStringOfLength(len int) string { +func (td *TestData) RandomStringOfLength(length int) string { // len should not be less then 1 or greater than 1024 - if 1 > len || len > 1024 { + if 1 > length || length > 1024 { panic("Invalid Test: RandomStringOfLength: length argument must be between 1 and 1024 characters") } - return randString(len) + return randString(length) } // randString generates a random alphanumeric string of the length specified diff --git a/internal/clients/auth.go b/internal/clients/auth.go index fdd169397940..fb3db4d8da8d 100644 --- a/internal/clients/auth.go +++ b/internal/clients/auth.go @@ -5,6 +5,7 @@ package clients import ( "context" + "errors" "fmt" "log" "net/http" @@ -93,7 +94,7 @@ func NewResourceManagerAccount(ctx context.Context, config auth.Credentials, sub // Use the tenant ID from Azure CLI when otherwise unknown if tenantId == "" { if cli.TenantID == "" { - return nil, fmt.Errorf("azure-cli could not determine tenant ID to use") + return nil, errors.New("azure-cli could not determine tenant ID to use") } tenantId = cli.TenantID log.Printf("[DEBUG] Using tenant ID from Azure CLI: %q", tenantId) @@ -108,10 +109,10 @@ func NewResourceManagerAccount(ctx context.Context, config auth.Credentials, sub // We'll permit the provider to proceed with an unknown client ID since it only affects a small number of use cases when authenticating as a user if tenantId == "" { - return nil, fmt.Errorf("unable to configure ResourceManagerAccount: tenant ID could not be determined and was not specified") + return nil, errors.New("unable to configure ResourceManagerAccount: tenant ID could not be determined and was not specified") } if subscriptionId == "" { - return nil, fmt.Errorf("unable to configure ResourceManagerAccount: subscription ID could not be determined and was not specified") + return nil, errors.New("unable to configure ResourceManagerAccount: subscription ID could not be determined and was not specified") } account := ResourceManagerAccount{ diff --git a/internal/clients/builder.go b/internal/clients/builder.go index e278fcd1ae8f..16c15ffd0132 100644 --- a/internal/clients/builder.go +++ b/internal/clients/builder.go @@ -114,7 +114,7 @@ func Build(ctx context.Context, builder ClientBuilder) (*Client, error) { resourceManagerEndpoint, ok := builder.AuthConfig.Environment.ResourceManager.Endpoint() if !ok { - return nil, fmt.Errorf("unable to determine resource manager endpoint for the current environment") + return nil, errors.New("unable to determine resource manager endpoint for the current environment") } client := Client{ diff --git a/internal/clients/client_gen.go b/internal/clients/client_gen.go index e5b1b50ad94d..d744304ea359 100644 --- a/internal/clients/client_gen.go +++ b/internal/clients/client_gen.go @@ -20,7 +20,6 @@ type autoClient struct { } func buildAutoClients(client *autoClient, o *common.ClientOptions) (err error) { - if client.ChaosStudio, err = chaosstudio.NewClient(o); err != nil { return fmt.Errorf("building client for ChaosStudio: %+v", err) } diff --git a/internal/clients/graph/client.go b/internal/clients/graph/client.go index d70ee4597a66..8c75740722a5 100644 --- a/internal/clients/graph/client.go +++ b/internal/clients/graph/client.go @@ -5,6 +5,7 @@ package graph import ( "context" + "errors" "fmt" "net/http" "time" @@ -100,7 +101,7 @@ func ServicePrincipalObjectID(ctx context.Context, authorizer auth.Authorizer, e id := model.ServicePrincipals[0].ID if id == nil { - return nil, fmt.Errorf("returned object ID was nil") + return nil, errors.New("returned object ID was nil") } return id, nil diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 2160d4a2893c..18ac16535842 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -553,7 +553,6 @@ func buildClient(ctx context.Context, p *schema.Provider, d *schema.ResourceData if err = resourceproviders.EnsureRegistered(ctx2, client.Resource.ResourceProvidersClient, subscriptionId, requiredResourceProviders); err != nil { return nil, diag.FromErr(err) - } return client, nil diff --git a/internal/sdk/frameworkhelpers/list.go b/internal/sdk/frameworkhelpers/list.go index fe2ee04ef8ce..b1757af42df1 100644 --- a/internal/sdk/frameworkhelpers/list.go +++ b/internal/sdk/frameworkhelpers/list.go @@ -83,7 +83,6 @@ func (w WrappedListValidator) ValidateList(ctx context.Context, request validato default: response.Diagnostics.AddError(fmt.Sprintf("unsupported list validation wrapper type for %s", path), fmt.Sprintf("%+v", request.ConfigValue)) } - } var _ validator.List = &WrappedListValidator{} diff --git a/internal/sdk/resource_decode.go b/internal/sdk/resource_decode.go index f7db50412de1..982edee9b46b 100644 --- a/internal/sdk/resource_decode.go +++ b/internal/sdk/resource_decode.go @@ -301,7 +301,6 @@ func setListValue(input interface{}, index int, fieldName string, v []interface{ } tmp.Elem().Set(slice) reflect.ValueOf(input).Elem().Field(index).Set(tmp) - } default: diff --git a/internal/sdk/resource_encode.go b/internal/sdk/resource_encode.go index ee8042c3ed50..8c2d4415f5d9 100644 --- a/internal/sdk/resource_encode.go +++ b/internal/sdk/resource_encode.go @@ -236,7 +236,6 @@ func recurse(objType reflect.Type, objVal reflect.Value, debugLogger Logger) (ou debugLogger.Infof("[SLICE] Setting %q to %+v", structTags.hclPath, attr) output[structTags.hclPath] = attr } - } } else { debugLogger.Infof("Setting %q to nil", structTags.hclPath) diff --git a/internal/sdk/resource_encode_test.go b/internal/sdk/resource_encode_test.go index 0ffffea5c41f..32b06ed4806d 100644 --- a/internal/sdk/resource_encode_test.go +++ b/internal/sdk/resource_encode_test.go @@ -384,15 +384,15 @@ func TestResourceEncode_TopLevelOmitted(t *testing.T) { func TestResourceEncode_TopLevelComputed(t *testing.T) { type SimpleType struct { - ComputedString string `tfschema:"computed_string" computed:"true"` - ComputedNumber int64 `tfschema:"computed_number" computed:"true"` - ComputedBool bool `tfschema:"computed_bool" computed:"true"` + ComputedString string `tfschema:"computed_string" computed:"true"` + ComputedNumber int64 `tfschema:"computed_number" computed:"true"` + ComputedBool bool `tfschema:"computed_bool" computed:"true"` ComputedListOfNumbers []int64 `tfschema:"computed_list_of_numbers" computed:"true"` ComputedListOfStrings []string `tfschema:"computed_list_of_strings" computed:"true"` - ComputedMapOfBools map[string]bool `tfschema:"computed_map_of_bools" computed:"true"` - ComputedMapOfFloats map[string]float64 `tfschema:"computed_map_of_floats" computed:"true"` - ComputedMapOfInts map[string]int64 `tfschema:"computed_map_of_ints" computed:"true"` - ComputedMapOfStrings map[string]string `tfschema:"computed_map_of_strings" computed:"true"` + ComputedMapOfBools map[string]bool `tfschema:"computed_map_of_bools" computed:"true"` + ComputedMapOfFloats map[string]float64 `tfschema:"computed_map_of_floats" computed:"true"` + ComputedMapOfInts map[string]int64 `tfschema:"computed_map_of_ints" computed:"true"` + ComputedMapOfStrings map[string]string `tfschema:"computed_map_of_strings" computed:"true"` } encodeTestData{ Input: &SimpleType{ @@ -573,9 +573,9 @@ func TestResourceEncode_NestedOneLevelDeepSingleOmittedValues(t *testing.T) { MapOfBools map[string]bool `tfschema:"map_of_bools"` MapOfNumbers map[string]int64 `tfschema:"map_of_numbers"` MapOfStrings map[string]string `tfschema:"map_of_strings"` - ComputedMapOfBools map[string]bool `tfschema:"computed_map_of_bools" computed:"true"` - ComputedMapOfFloats map[string]float64 `tfschema:"computed_map_of_floats" computed:"true"` - ComputedMapOfInts map[string]int64 `tfschema:"computed_map_of_ints" computed:"true"` + ComputedMapOfBools map[string]bool `tfschema:"computed_map_of_bools" computed:"true"` + ComputedMapOfFloats map[string]float64 `tfschema:"computed_map_of_floats" computed:"true"` + ComputedMapOfInts map[string]int64 `tfschema:"computed_map_of_ints" computed:"true"` ComputedMapOfStrings map[string]string `tfschema:"computed_map_of_strings" computed:"true"` } type Type struct { diff --git a/internal/sdk/resource_test.go b/internal/sdk/resource_test.go index 546142b47a58..148cdf9c7111 100644 --- a/internal/sdk/resource_test.go +++ b/internal/sdk/resource_test.go @@ -8,7 +8,7 @@ package sdk type ExampleObj struct { Name string `tfschema:"name"` Number int `tfschema:"number"` - Output string `tfschema:"output" computed:"true"` + Output string `tfschema:"output" computed:"true"` Enabled bool `tfschema:"enabled"` Networks []string `tfschema:"networks"` NetworksSet []string `tfschema:"networks_set"` diff --git a/internal/services/aadb2c/aadb2c_directory_resource.go b/internal/services/aadb2c/aadb2c_directory_resource.go index 787d70b4e058..9ec1cc3b439c 100644 --- a/internal/services/aadb2c/aadb2c_directory_resource.go +++ b/internal/services/aadb2c/aadb2c_directory_resource.go @@ -5,6 +5,7 @@ package aadb2c import ( "context" + "errors" "fmt" "time" @@ -144,10 +145,10 @@ func (r AadB2cDirectoryResource) Create() sdk.ResourceFunc { } if model.CountryCode == "" { - return fmt.Errorf("`country_code` is required when creating a new AADB2C directory") + return errors.New("`country_code` is required when creating a new AADB2C directory") } if model.DisplayName == "" { - return fmt.Errorf("`display_name` is required when creating a new AADB2C directory") + return errors.New("`display_name` is required when creating a new AADB2C directory") } id := tenants.NewB2CDirectoryID(subscriptionId, model.ResourceGroup, model.DomainName) diff --git a/internal/services/advisor/advisor_recommendations_data_source.go b/internal/services/advisor/advisor_recommendations_data_source.go index e6f8ebf9c3ed..e8c3c86b16f2 100644 --- a/internal/services/advisor/advisor_recommendations_data_source.go +++ b/internal/services/advisor/advisor_recommendations_data_source.go @@ -132,7 +132,7 @@ func dataSourceAdvisorRecommendationsRead(d *pluginsdk.ResourceData, meta interf return fmt.Errorf("setting `recommendations`: %+v", err) } - d.SetId(fmt.Sprintf("avdisor/recommendations/%s", time.Now().UTC().String())) + d.SetId("avdisor/recommendations/" + time.Now().UTC().String()) return nil } diff --git a/internal/services/apimanagement/api_management_api_operation_policy_resource.go b/internal/services/apimanagement/api_management_api_operation_policy_resource.go index 7ea4e6a483d7..5752810d48c6 100644 --- a/internal/services/apimanagement/api_management_api_operation_policy_resource.go +++ b/internal/services/apimanagement/api_management_api_operation_policy_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "html" "log" @@ -112,7 +113,7 @@ func resourceApiManagementAPIOperationPolicyCreateUpdate(d *pluginsdk.ResourceDa } if parameters.Properties == nil { - return fmt.Errorf("Either `xml_content` or `xml_link` must be set") + return errors.New("Either `xml_content` or `xml_link` must be set") } if _, err := client.CreateOrUpdate(ctx, id, parameters, apioperationpolicy.CreateOrUpdateOperationOptions{}); err != nil { diff --git a/internal/services/apimanagement/api_management_api_policy_resource.go b/internal/services/apimanagement/api_management_api_policy_resource.go index 63a2618d7a68..44f360ce763a 100644 --- a/internal/services/apimanagement/api_management_api_policy_resource.go +++ b/internal/services/apimanagement/api_management_api_policy_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "html" "log" @@ -115,7 +116,7 @@ func resourceApiManagementAPIPolicyCreateUpdate(d *pluginsdk.ResourceData, meta } if parameters.Properties == nil { - return fmt.Errorf("Either `xml_content` or `xml_link` must be set") + return errors.New("Either `xml_content` or `xml_link` must be set") } if _, err := client.CreateOrUpdate(ctx, id, parameters, apipolicy.CreateOrUpdateOperationOptions{}); err != nil { diff --git a/internal/services/apimanagement/api_management_api_resource.go b/internal/services/apimanagement/api_management_api_resource.go index 994200a17332..e0ba5c30dd32 100644 --- a/internal/services/apimanagement/api_management_api_resource.go +++ b/internal/services/apimanagement/api_management_api_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "log" "strings" @@ -370,11 +371,11 @@ func resourceApiManagementApiCreateUpdate(d *pluginsdk.ResourceData, meta interf id := api.NewApiID(subscriptionId, d.Get("resource_group_name").(string), d.Get("api_management_name").(string), apiId) if version != "" && versionSetId == "" { - return fmt.Errorf("setting `version` without the required `version_set_id`") + return errors.New("setting `version` without the required `version_set_id`") } if sourceApiId == "" && (displayName == "" || protocols == nil || len(*protocols) == 0) { - return fmt.Errorf("`display_name`, `protocols` are required when `source_api_id` is not set") + return errors.New("`display_name`, `protocols` are required when `source_api_id` is not set") } newId := api.NewApiID(subscriptionId, d.Get("resource_group_name").(string), d.Get("api_management_name").(string), apiId) diff --git a/internal/services/apimanagement/api_management_api_version_set_resource.go b/internal/services/apimanagement/api_management_api_version_set_resource.go index c7de3d85d6b0..78bf2ccc8140 100644 --- a/internal/services/apimanagement/api_management_api_version_set_resource.go +++ b/internal/services/apimanagement/api_management_api_version_set_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "log" "time" @@ -134,26 +135,26 @@ func resourceApiManagementApiVersionSetCreateUpdate(d *pluginsdk.ResourceData, m switch schema := versioningScheme; schema { case apiversionset.VersioningSchemeHeader: if !headerSet { - return fmt.Errorf("`version_header_name` must be set if `versioning_schema` is `Header`") + return errors.New("`version_header_name` must be set if `versioning_schema` is `Header`") } if querySet { - return fmt.Errorf("`version_query_name` can not be set if `versioning_schema` is `Header`") + return errors.New("`version_query_name` can not be set if `versioning_schema` is `Header`") } case apiversionset.VersioningSchemeQuery: if headerSet { - return fmt.Errorf("`version_header_name` can not be set if `versioning_schema` is `Query`") + return errors.New("`version_header_name` can not be set if `versioning_schema` is `Query`") } if !querySet { - return fmt.Errorf("`version_query_name` must be set if `versioning_schema` is `Query`") + return errors.New("`version_query_name` must be set if `versioning_schema` is `Query`") } case apiversionset.VersioningSchemeSegment: if headerSet { - return fmt.Errorf("`version_header_name` can not be set if `versioning_schema` is `Segment`") + return errors.New("`version_header_name` can not be set if `versioning_schema` is `Segment`") } if querySet { - return fmt.Errorf("`version_query_name` can not be set if `versioning_schema` is `Segment`") + return errors.New("`version_query_name` can not be set if `versioning_schema` is `Segment`") } } diff --git a/internal/services/apimanagement/api_management_backend_resource.go b/internal/services/apimanagement/api_management_backend_resource.go index 3c7f8a130594..650d69c2a9e0 100644 --- a/internal/services/apimanagement/api_management_backend_resource.go +++ b/internal/services/apimanagement/api_management_backend_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "log" "strings" @@ -483,7 +484,7 @@ func expandApiManagementBackendServiceFabricCluster(input []interface{}) (error, } if properties.ClientCertificateId == nil && properties.ClientCertificatethumbprint == nil { - return fmt.Errorf("at least one of `client_certificate_thumbprint` and `client_certificate_id` must be set"), nil + return errors.New("at least one of `client_certificate_thumbprint` and `client_certificate_id` must be set"), nil } serverCertificateThumbprintsUnset := true @@ -497,7 +498,7 @@ func expandApiManagementBackendServiceFabricCluster(input []interface{}) (error, serverX509NamesUnset = false } if serverCertificateThumbprintsUnset && serverX509NamesUnset { - return fmt.Errorf("One of `server_certificate_thumbprints` or `server_x509_name` must be set"), nil + return errors.New("one of `server_certificate_thumbprints` or `server_x509_name` must be set"), nil } return nil, &properties } diff --git a/internal/services/apimanagement/api_management_logger_resource.go b/internal/services/apimanagement/api_management_logger_resource.go index f3219b0e4ad0..b78dad04b59e 100644 --- a/internal/services/apimanagement/api_management_logger_resource.go +++ b/internal/services/apimanagement/api_management_logger_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "log" "time" @@ -170,7 +171,7 @@ func resourceApiManagementLoggerCreate(d *pluginsdk.ResourceData, meta interface appInsightsRaw := d.Get("application_insights").([]interface{}) if len(eventHubRaw) == 0 && len(appInsightsRaw) == 0 { - return fmt.Errorf("Either `eventhub` or `application_insights` is required") + return errors.New("either `eventhub` or `application_insights` is required") } if d.IsNewResource() { @@ -324,7 +325,6 @@ func expandApiManagementLoggerEventHub(input []interface{}) *map[string]string { if clientId != "" { credentials["identityClientId"] = clientId } - } return &credentials diff --git a/internal/services/apimanagement/api_management_named_value_resource.go b/internal/services/apimanagement/api_management_named_value_resource.go index d8e82655f16a..3848194aa28d 100644 --- a/internal/services/apimanagement/api_management_named_value_resource.go +++ b/internal/services/apimanagement/api_management_named_value_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "log" "time" @@ -131,7 +132,7 @@ func resourceApiManagementNamedValueCreateUpdate(d *pluginsdk.ResourceData, meta } if parameters.Properties.KeyVault != nil && (parameters.Properties.Secret == nil || !*parameters.Properties.Secret) { - return fmt.Errorf("`secret` must be true when `value_from_key_vault` is set") + return errors.New("`secret` must be true when `value_from_key_vault` is set") } if v, ok := d.GetOk("value"); ok { diff --git a/internal/services/apimanagement/api_management_policy_resource.go b/internal/services/apimanagement/api_management_policy_resource.go index 7aa1a221d427..b02474d3137d 100644 --- a/internal/services/apimanagement/api_management_policy_resource.go +++ b/internal/services/apimanagement/api_management_policy_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "html" "log" @@ -116,7 +117,7 @@ func resourceApiManagementPolicyCreateUpdate(d *pluginsdk.ResourceData, meta int } if parameters.Properties == nil { - return fmt.Errorf("Either `xml_content` or `xml_link` must be set") + return errors.New("Either `xml_content` or `xml_link` must be set") } policyServiceId := policy.NewServiceID(apiMgmtId.SubscriptionId, resourceGroup, serviceName) diff --git a/internal/services/apimanagement/api_management_product_policy_resource.go b/internal/services/apimanagement/api_management_product_policy_resource.go index 67e2df8d6733..8da02e763f20 100644 --- a/internal/services/apimanagement/api_management_product_policy_resource.go +++ b/internal/services/apimanagement/api_management_product_policy_resource.go @@ -4,6 +4,7 @@ package apimanagement import ( + "errors" "fmt" "html" "log" @@ -110,7 +111,7 @@ func resourceApiManagementProductPolicyCreateUpdate(d *pluginsdk.ResourceData, m } if parameters.Properties == nil { - return fmt.Errorf("Either `xml_content` or `xml_link` must be set") + return errors.New("either `xml_content` or `xml_link` must be set") } if _, err := client.CreateOrUpdate(ctx, id, parameters, productpolicy.CreateOrUpdateOperationOptions{}); err != nil { diff --git a/internal/services/apimanagement/api_management_resource.go b/internal/services/apimanagement/api_management_resource.go index f82b093aea1d..821e5fc4e310 100644 --- a/internal/services/apimanagement/api_management_resource.go +++ b/internal/services/apimanagement/api_management_resource.go @@ -803,7 +803,7 @@ func resourceApiManagementServiceCreate(d *pluginsdk.ResourceData, meta interfac if virtualNetworkType != string(apimanagementservice.VirtualNetworkTypeNone) { virtualNetworkConfiguration := expandAzureRmApiManagementVirtualNetworkConfigurations(d) if virtualNetworkConfiguration == nil { - return fmt.Errorf("You must specify 'virtual_network_configuration' when 'virtual_network_type' is %q", virtualNetworkType) + return fmt.Errorf("you must specify 'virtual_network_configuration' when 'virtual_network_type' is %q", virtualNetworkType) } properties.Properties.VirtualNetworkConfiguration = virtualNetworkConfiguration } @@ -812,7 +812,7 @@ func resourceApiManagementServiceCreate(d *pluginsdk.ResourceData, meta interfac if publicIpAddressId != "" { if sku.Name != apimanagementservice.SkuTypePremium && sku.Name != apimanagementservice.SkuTypeDeveloper { if virtualNetworkType == string(apimanagementservice.VirtualNetworkTypeNone) { - return fmt.Errorf("`public_ip_address_id` is only supported when sku type is `Developer` or `Premium`, and the APIM instance is deployed in a virtual network.") + return errors.New("`public_ip_address_id` is only supported when sku type is `Developer` or `Premium`, and the APIM instance is deployed in a virtual network") } } properties.Properties.PublicIPAddressId = pointer.To(publicIpAddressId) @@ -821,14 +821,14 @@ func resourceApiManagementServiceCreate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("client_certificate_enabled") { enableClientCertificate := d.Get("client_certificate_enabled").(bool) if enableClientCertificate && sku.Name != apimanagementservice.SkuTypeConsumption { - return fmt.Errorf("`client_certificate_enabled` is only supported when sku type is `Consumption`") + return errors.New("`client_certificate_enabled` is only supported when sku type is `Consumption`") } properties.Properties.EnableClientCertificate = pointer.To(enableClientCertificate) } gateWayDisabled := d.Get("gateway_disabled").(bool) if gateWayDisabled && len(*properties.Properties.AdditionalLocations) == 0 { - return fmt.Errorf("`gateway_disabled` is only supported when `additional_location` is set") + return errors.New("`gateway_disabled` is only supported when `additional_location` is set") } properties.Properties.DisableGateway = pointer.To(gateWayDisabled) @@ -840,11 +840,11 @@ func resourceApiManagementServiceCreate(d *pluginsdk.ResourceData, meta interfac if v := d.Get("zones").(*schema.Set).List(); len(v) > 0 { if sku.Name != apimanagementservice.SkuTypePremium { - return fmt.Errorf("`zones` is only supported when sku type is `Premium`") + return errors.New("`zones` is only supported when sku type is `Premium`") } if publicIpAddressId == "" { - return fmt.Errorf("`public_ip_address` must be specified when `zones` are provided") + return errors.New("`public_ip_address` must be specified when `zones` are provided") } zones := zones.ExpandUntyped(v) properties.Zones = &zones @@ -906,7 +906,7 @@ func resourceApiManagementServiceCreate(d *pluginsdk.ResourceData, meta interfac signInSettingsRaw := d.Get("sign_in").([]interface{}) if sku.Name == apimanagementservice.SkuTypeConsumption && len(signInSettingsRaw) > 0 { - return fmt.Errorf("`sign_in` is not support for sku tier `Consumption`") + return errors.New("`sign_in` is not support for sku tier `Consumption`") } if sku.Name != apimanagementservice.SkuTypeConsumption { signInSettingServiceId := signinsettings.NewServiceID(subscriptionId, id.ResourceGroupName, id.ServiceName) @@ -1104,7 +1104,7 @@ func resourceApiManagementServiceUpdate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("client_certificate_enabled") { enableClientCertificate := d.Get("client_certificate_enabled").(bool) if enableClientCertificate && sku.Name != apimanagementservice.SkuTypeConsumption { - return fmt.Errorf("`client_certificate_enabled` is only supported when sku type is `Consumption`") + return errors.New("`client_certificate_enabled` is only supported when sku type is `Consumption`") } props.EnableClientCertificate = pointer.To(enableClientCertificate) } @@ -1112,7 +1112,7 @@ func resourceApiManagementServiceUpdate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("gateway_disabled") { gateWayDisabled := d.Get("gateway_disabled").(bool) if gateWayDisabled && props.AdditionalLocations != nil && len(*props.AdditionalLocations) == 0 { - return fmt.Errorf("`gateway_disabled` is only supported when `additional_location` is set") + return errors.New("`gateway_disabled` is only supported when `additional_location` is set") } props.DisableGateway = pointer.To(gateWayDisabled) } @@ -1130,11 +1130,11 @@ func resourceApiManagementServiceUpdate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("zones") { if v := d.Get("zones").(*schema.Set).List(); len(v) > 0 { if sku.Name != apimanagementservice.SkuTypePremium { - return fmt.Errorf("`zones` is only supported when sku type is `Premium`") + return errors.New("`zones` is only supported when sku type is `Premium`") } if d.Get("public_ip_address_id").(string) == "" { - return fmt.Errorf("`public_ip_address` must be specified when `zones` are provided") + return errors.New("`public_ip_address` must be specified when `zones` are provided") } zones := zones.ExpandUntyped(v) payload.Zones = &zones @@ -1152,7 +1152,7 @@ func resourceApiManagementServiceUpdate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("sign_in") { signInSettingsRaw := d.Get("sign_in").([]interface{}) if sku.Name == apimanagementservice.SkuTypeConsumption && len(signInSettingsRaw) > 0 { - return fmt.Errorf("`sign_in` is not support for sku tier `Consumption`") + return errors.New("`sign_in` is not support for sku tier `Consumption`") } if sku.Name != apimanagementservice.SkuTypeConsumption { signInSettingServiceId := signinsettings.NewServiceID(subscriptionId, id.ResourceGroupName, id.ServiceName) @@ -1167,7 +1167,7 @@ func resourceApiManagementServiceUpdate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("sign_up") { signUpSettingsRaw := d.Get("sign_up").([]interface{}) if sku.Name == apimanagementservice.SkuTypeConsumption && len(signUpSettingsRaw) > 0 { - return fmt.Errorf("`sign_up` is not support for sku tier `Consumption`") + return errors.New("`sign_up` is not support for sku tier `Consumption`") } if sku.Name != apimanagementservice.SkuTypeConsumption { signUpSettingServiceId := signupsettings.NewServiceID(subscriptionId, id.ResourceGroupName, id.ServiceName) @@ -1182,7 +1182,7 @@ func resourceApiManagementServiceUpdate(d *pluginsdk.ResourceData, meta interfac if d.HasChange("delegation") { delegationSettingsRaw := d.Get("delegation").([]interface{}) if sku.Name == apimanagementservice.SkuTypeConsumption && len(delegationSettingsRaw) > 0 { - return fmt.Errorf("`delegation` is not support for sku tier `Consumption`") + return errors.New("`delegation` is not support for sku tier `Consumption`") } if sku.Name != apimanagementservice.SkuTypeConsumption && len(delegationSettingsRaw) > 0 { delegationSettingServiceId := delegationsettings.NewServiceID(subscriptionId, id.ResourceGroupName, id.ServiceName) @@ -1694,9 +1694,9 @@ func expandAzureRmApiManagementAdditionalLocations(d *pluginsdk.ResourceData, sk childVnetConfig := config["virtual_network_configuration"].([]interface{}) switch { case len(childVnetConfig) == 0 && len(parentVnetConfig) > 0: - return nil, fmt.Errorf("`virtual_network_configuration` must be specified in any `additional_location` block when top-level `virtual_network_configuration` is supplied") + return nil, errors.New("`virtual_network_configuration` must be specified in any `additional_location` block when top-level `virtual_network_configuration` is supplied") case len(childVnetConfig) > 0 && len(parentVnetConfig) == 0: - return nil, fmt.Errorf("`virtual_network_configuration` must be empty in all `additional_location` blocks when top-level `virtual_network_configuration` is not supplied") + return nil, errors.New("`virtual_network_configuration` must be empty in all `additional_location` blocks when top-level `virtual_network_configuration` is not supplied") case len(childVnetConfig) > 0 && len(parentVnetConfig) > 0: v := childVnetConfig[0].(map[string]interface{}) subnetResourceId := v["subnet_id"].(string) @@ -1709,7 +1709,7 @@ func expandAzureRmApiManagementAdditionalLocations(d *pluginsdk.ResourceData, sk if publicIPAddressID != "" { if sku.Name != apimanagementservice.SkuTypePremium { if len(childVnetConfig) == 0 { - return nil, fmt.Errorf("`public_ip_address_id` for an additional location is only supported when sku type is `Premium`, and the APIM instance is deployed in a virtual network.") + return nil, errors.New("`public_ip_address_id` for an additional location is only supported when sku type is `Premium`, and the APIM instance is deployed in a virtual network.") } } additionalLocation.PublicIPAddressId = &publicIPAddressID @@ -1817,47 +1817,47 @@ func expandApiManagementCustomProperties(d *pluginsdk.ResourceData, skuIsConsump tlsRsaWithAes128CbcShaCiphers = v["tls_rsa_with_aes128_cbc_sha_ciphers_enabled"].(bool) if skuIsConsumption && frontendProtocolSsl3 { - return nil, fmt.Errorf("`enable_frontend_ssl30` is not support for Sku Tier `Consumption`") + return nil, errors.New("`enable_frontend_ssl30` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tripleDesCiphers { - return nil, fmt.Errorf("`enable_triple_des_ciphers` is not support for Sku Tier `Consumption`") + return nil, errors.New("`enable_triple_des_ciphers` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsEcdheEcdsaWithAes256CbcShaCiphers { - return nil, fmt.Errorf("`tls_ecdhe_ecdsa_with_aes256_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_ecdhe_ecdsa_with_aes256_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsEcdheEcdsaWithAes128CbcShaCiphers { - return nil, fmt.Errorf("`tls_ecdhe_ecdsa_with_aes128_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_ecdhe_ecdsa_with_aes128_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsEcdheRsaWithAes256CbcShaCiphers { - return nil, fmt.Errorf("`tls_ecdhe_rsa_with_aes256_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_ecdhe_rsa_with_aes256_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsEcdheRsaWithAes128CbcShaCiphers { - return nil, fmt.Errorf("`tls_ecdhe_rsa_with_aes128_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_ecdhe_rsa_with_aes128_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsRsaWithAes128GcmSha256Ciphers { - return nil, fmt.Errorf("`tls_rsa_with_aes128_gcm_sha256_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_rsa_with_aes128_gcm_sha256_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsRsaWithAes256CbcSha256Ciphers { - return nil, fmt.Errorf("`tls_rsa_with_aes256_cbc_sha256_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_rsa_with_aes256_cbc_sha256_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsRsaWithAes128CbcSha256Ciphers { - return nil, fmt.Errorf("`tls_rsa_with_aes128_cbc_sha256_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_rsa_with_aes128_cbc_sha256_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsRsaWithAes256CbcShaCiphers { - return nil, fmt.Errorf("`tls_rsa_with_aes256_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_rsa_with_aes256_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") } if skuIsConsumption && tlsRsaWithAes128CbcShaCiphers { - return nil, fmt.Errorf("`tls_rsa_with_aes128_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") + return nil, errors.New("`tls_rsa_with_aes128_cbc_sha_ciphers_enabled` is not support for Sku Tier `Consumption`") } } @@ -2160,7 +2160,7 @@ func expandApiManagementPolicies(input []interface{}) (*policy.PolicyContract, e }, nil } - return nil, fmt.Errorf("Either `xml_content` or `xml_link` should be set if the `policy` block is defined.") + return nil, errors.New("Either `xml_content` or `xml_link` should be set if the `policy` block is defined.") } func flattenApiManagementPolicies(d *pluginsdk.ResourceData, input *policy.PolicyContract) []interface{} { diff --git a/internal/services/appconfiguration/app_configuration_feature_resource.go b/internal/services/appconfiguration/app_configuration_feature_resource.go index 4903258b022c..c29fc084ada0 100644 --- a/internal/services/appconfiguration/app_configuration_feature_resource.go +++ b/internal/services/appconfiguration/app_configuration_feature_resource.go @@ -6,6 +6,7 @@ package appconfiguration import ( "context" "encoding/json" + "errors" "fmt" "log" "strings" @@ -215,7 +216,7 @@ func (k FeatureResource) Create() sdk.ResourceFunc { deadline, ok := ctx.Deadline() if !ok { - return fmt.Errorf("internal-error: context had no deadline") + return errors.New("internal-error: context had no deadline") } // from https://learn.microsoft.com/en-us/azure/azure-app-configuration/concept-enable-rbac#azure-built-in-roles-for-azure-app-configuration @@ -392,7 +393,7 @@ func (k FeatureResource) Read() sdk.ResourceFunc { ConfigurationStoreId: configurationStoreId.ID(), Description: fv.Description, Enabled: fv.Enabled, - Key: strings.TrimPrefix(pointer.From(kv.Key), fmt.Sprintf("%s/", FeatureKeyPrefix)), + Key: strings.TrimPrefix(pointer.From(kv.Key), FeatureKeyPrefix+"/"), Name: fv.ID, Label: pointer.From(kv.Label), Tags: tags.Flatten(kv.Tags), diff --git a/internal/services/appconfiguration/app_configuration_key_resource.go b/internal/services/appconfiguration/app_configuration_key_resource.go index bd9d29a284cc..93411621a3be 100644 --- a/internal/services/appconfiguration/app_configuration_key_resource.go +++ b/internal/services/appconfiguration/app_configuration_key_resource.go @@ -6,6 +6,7 @@ package appconfiguration import ( "context" "encoding/json" + "errors" "fmt" "log" "time" @@ -162,7 +163,7 @@ func (k KeyResource) Create() sdk.ResourceFunc { deadline, ok := ctx.Deadline() if !ok { - return fmt.Errorf("internal-error: context had no deadline") + return errors.New("internal-error: context had no deadline") } // from https://learn.microsoft.com/en-us/azure/azure-app-configuration/concept-enable-rbac#azure-built-in-roles-for-azure-app-configuration diff --git a/internal/services/appconfiguration/app_configuration_resource.go b/internal/services/appconfiguration/app_configuration_resource.go index eed5d5f33120..0615cf1639da 100644 --- a/internal/services/appconfiguration/app_configuration_resource.go +++ b/internal/services/appconfiguration/app_configuration_resource.go @@ -372,7 +372,6 @@ func resourceAppConfigurationCreate(d *pluginsdk.ResourceData, meta interface{}) if err := replicaClient.CreateThenPoll(ctx, replicaId, replica); err != nil { return fmt.Errorf("creating %s: %+v", replicaId, err) } - } return resourceAppConfigurationRead(d, meta) diff --git a/internal/services/appconfiguration/feature_structs.go b/internal/services/appconfiguration/feature_structs.go index b3cc63c4f160..062bc764181d 100644 --- a/internal/services/appconfiguration/feature_structs.go +++ b/internal/services/appconfiguration/feature_structs.go @@ -107,7 +107,7 @@ type PercentageFeatureFilter struct { } type TargetingGroupParameter struct { - Name string `json:"Name" tfschema:"name"` + Name string `json:"Name" tfschema:"name"` RolloutPercentage int64 `json:"RolloutPercentage" tfschema:"rollout_percentage"` } @@ -117,8 +117,8 @@ type TargetingFilterParameters struct { type TargetingFilterAudience struct { DefaultRolloutPercentage int64 `json:"DefaultRolloutPercentage" tfschema:"default_rollout_percentage"` - Users []string `json:"Users" tfschema:"users"` - Groups []TargetingGroupParameter `json:"Groups" tfschema:"groups"` + Users []string `json:"Users" tfschema:"users"` + Groups []TargetingGroupParameter `json:"Groups" tfschema:"groups"` } type TargetingFeatureFilter struct { @@ -128,7 +128,7 @@ type TargetingFeatureFilter struct { type TimewindowFilterParameters struct { Start string `json:"Start" tfschema:"start"` - End string `json:"End" tfschema:"end"` + End string `json:"End" tfschema:"end"` } type TimewindowFeatureFilter struct { diff --git a/internal/services/appconfiguration/parse/app_configuration_key.go b/internal/services/appconfiguration/parse/app_configuration_key.go index 78f81d9a72a6..f50ca78fe9e3 100644 --- a/internal/services/appconfiguration/parse/app_configuration_key.go +++ b/internal/services/appconfiguration/parse/app_configuration_key.go @@ -74,5 +74,4 @@ func handleSlashInIdForKey(input string) string { } return input - } diff --git a/internal/services/applicationinsights/application_insights_resource.go b/internal/services/applicationinsights/application_insights_resource.go index 54c732d8879a..b2011f6abd82 100644 --- a/internal/services/applicationinsights/application_insights_resource.go +++ b/internal/services/applicationinsights/application_insights_resource.go @@ -316,7 +316,6 @@ func resourceApplicationInsightsCreateUpdate(d *pluginsdk.ResourceData, meta int return pluginsdk.NonRetryableError(fmt.Errorf("issuing disable request for %s: %+v", ruleId, err)) } } - } } diff --git a/internal/services/applicationinsights/application_insights_smart_detection_rule_resource.go b/internal/services/applicationinsights/application_insights_smart_detection_rule_resource.go index a7f5bf06e22f..ceb8848ec194 100644 --- a/internal/services/applicationinsights/application_insights_smart_detection_rule_resource.go +++ b/internal/services/applicationinsights/application_insights_smart_detection_rule_resource.go @@ -159,7 +159,6 @@ func resourceApplicationInsightsSmartDetectionRuleRead(d *pluginsdk.ResourceData d.Set("enabled", model.Enabled) d.Set("send_emails_to_subscription_owners", model.SendEmailsToSubscriptionOwners) d.Set("additional_email_recipients", utils.FlattenStringSlice(model.CustomEmails)) - } return nil } diff --git a/internal/services/applicationinsights/application_insights_workbook_template_resource.go b/internal/services/applicationinsights/application_insights_workbook_template_resource.go index 7b22f59a3f94..c205884a681e 100644 --- a/internal/services/applicationinsights/application_insights_workbook_template_resource.go +++ b/internal/services/applicationinsights/application_insights_workbook_template_resource.go @@ -371,7 +371,7 @@ func (r ApplicationInsightsWorkbookTemplateResource) Delete() sdk.ResourceFunc { } func expandWorkbookTemplateGalleryModel(inputList []WorkbookTemplateGalleryModel) *[]workbooktemplates.WorkbookTemplateGallery { - var outputList []workbooktemplates.WorkbookTemplateGallery + outputList := make([]workbooktemplates.WorkbookTemplateGallery, 0, len(inputList)) for _, input := range inputList { output := workbooktemplates.WorkbookTemplateGallery{ Category: utils.String(input.Category), @@ -388,11 +388,11 @@ func expandWorkbookTemplateGalleryModel(inputList []WorkbookTemplateGalleryModel } func flattenWorkbookTemplateGalleryModel(inputList *[]workbooktemplates.WorkbookTemplateGallery) []WorkbookTemplateGalleryModel { - var outputList []WorkbookTemplateGalleryModel if inputList == nil { - return outputList + return []WorkbookTemplateGalleryModel{} } + outputList := make([]WorkbookTemplateGalleryModel, 0, len(*inputList)) for _, input := range *inputList { output := WorkbookTemplateGalleryModel{} diff --git a/internal/services/appservice/app_service_environment_v3_data_source.go b/internal/services/appservice/app_service_environment_v3_data_source.go index 9a8554ff14a2..513a92d96e44 100644 --- a/internal/services/appservice/app_service_environment_v3_data_source.go +++ b/internal/services/appservice/app_service_environment_v3_data_source.go @@ -259,7 +259,6 @@ func (r AppServiceEnvironmentV3DataSource) Read() sdk.ResourceFunc { state.InboundNetworkDependencies = *inboundNetworkDependencies state.Tags = pointer.From(model.Tags) - } metadata.SetID(id) diff --git a/internal/services/appservice/app_service_environment_v3_resource.go b/internal/services/appservice/app_service_environment_v3_resource.go index a66b2493846f..1d6ef42a16ff 100644 --- a/internal/services/appservice/app_service_environment_v3_resource.go +++ b/internal/services/appservice/app_service_environment_v3_resource.go @@ -517,11 +517,11 @@ func (r AppServiceEnvironmentV3Resource) Update() sdk.ResourceFunc { } func flattenClusterSettingsModel(input *[]appserviceenvironments.NameValuePair) []ClusterSettingModel { - var output []ClusterSettingModel if input == nil || len(*input) == 0 { - return output + return []ClusterSettingModel{} } + output := make([]ClusterSettingModel, 0, len(*input)) for _, v := range *input { if v.Name == nil { continue @@ -536,7 +536,7 @@ func flattenClusterSettingsModel(input *[]appserviceenvironments.NameValuePair) } func expandClusterSettingsModel(input []ClusterSettingModel) *[]appserviceenvironments.NameValuePair { - var clusterSettings []appserviceenvironments.NameValuePair + clusterSettings := make([]appserviceenvironments.NameValuePair, 0, len(input)) if input == nil { return &clusterSettings } @@ -552,11 +552,12 @@ func expandClusterSettingsModel(input []ClusterSettingModel) *[]appserviceenviro } func flattenInboundNetworkDependencies(ctx context.Context, client *appserviceenvironments.AppServiceEnvironmentsClient, id *commonids.AppServiceEnvironmentId) (*[]AppServiceV3InboundDependencies, error) { - var results []AppServiceV3InboundDependencies inboundNetworking, err := client.GetInboundNetworkDependenciesEndpointsComplete(ctx, *id) if err != nil { return nil, fmt.Errorf("reading paged results for Inbound Network Dependencies for %s: %+v", id, err) } + + results := make([]AppServiceV3InboundDependencies, 0, len(inboundNetworking.Items)) for _, v := range inboundNetworking.Items { if err != nil { return nil, fmt.Errorf("reading Inbound Network dependencies for %s: %+v", id, err) diff --git a/internal/services/appservice/function_app_hybrid_connection_resource.go b/internal/services/appservice/function_app_hybrid_connection_resource.go index 450262b132cf..ef44e37c169c 100644 --- a/internal/services/appservice/function_app_hybrid_connection_resource.go +++ b/internal/services/appservice/function_app_hybrid_connection_resource.go @@ -216,7 +216,6 @@ func (r FunctionAppHybridConnectionResource) Read() sdk.ResourceFunc { } if model := existing.Model; model != nil { - if props := model.Properties; props != nil { appHybridConn.RelayId = pointer.From(props.RelayArmUri) appHybridConn.HostName = pointer.From(props.Hostname) diff --git a/internal/services/appservice/helpers/app_stack.go b/internal/services/appservice/helpers/app_stack.go index e38a96e577a2..1f2627e3b4f9 100644 --- a/internal/services/appservice/helpers/app_stack.go +++ b/internal/services/appservice/helpers/app_stack.go @@ -299,7 +299,6 @@ func windowsApplicationStackSchema() *pluginsdk.Schema { MaxItems: 1, Elem: r, } - } func windowsApplicationStackSchemaComputed() *pluginsdk.Schema { @@ -403,7 +402,6 @@ func windowsApplicationStackSchemaComputed() *pluginsdk.Schema { Type: pluginsdk.TypeString, Computed: true, } - } return &pluginsdk.Schema{ Type: pluginsdk.TypeList, @@ -626,7 +624,6 @@ func linuxApplicationStackSchema() *pluginsdk.Schema { r.Schema["docker_registry_url"].Computed = true r.Schema["docker_registry_username"].Computed = true r.Schema["docker_registry_password"].Computed = true - } return &pluginsdk.Schema{ diff --git a/internal/services/appservice/helpers/auth_v2_schema.go b/internal/services/appservice/helpers/auth_v2_schema.go index 25f3b73f0ea8..d1a2d5cb40b6 100644 --- a/internal/services/appservice/helpers/auth_v2_schema.go +++ b/internal/services/appservice/helpers/auth_v2_schema.go @@ -1035,7 +1035,6 @@ func flattenAadAuthV2Settings(input *webapps.AzureActiveDirectory) []AadAuthV2Se } result.LoginParameters = loginParams } - } if validation := input.Validation; validation != nil { @@ -1782,7 +1781,6 @@ func expandGoogleAuthV2Settings(input []GoogleAuthV2Settings) *webapps.Google { Scopes: pointer.To(google.LoginScopes), }, } - } return &webapps.Google{ diff --git a/internal/services/appservice/helpers/common_web_app_schema.go b/internal/services/appservice/helpers/common_web_app_schema.go index 86af20310ed6..9d3e0c4fbc48 100644 --- a/internal/services/appservice/helpers/common_web_app_schema.go +++ b/internal/services/appservice/helpers/common_web_app_schema.go @@ -1257,7 +1257,7 @@ func FlattenStorageAccounts(appStorageAccounts *webapps.AzureStoragePropertyDict return []StorageAccount{} } - var storageAccounts []StorageAccount + storageAccounts := make([]StorageAccount, 0, len(*appStorageAccounts.Properties)) for k, v := range *appStorageAccounts.Properties { storageAccount := StorageAccount{ Name: k, @@ -1289,7 +1289,8 @@ func FlattenConnectionStrings(appConnectionStrings *webapps.ConnectionStringDict if appConnectionStrings.Properties == nil || len(*appConnectionStrings.Properties) == 0 { return []ConnectionString{} } - var connectionStrings []ConnectionString + + connectionStrings := make([]ConnectionString, 0, len(*appConnectionStrings.Properties)) for k, v := range *appConnectionStrings.Properties { connectionString := ConnectionString{ Name: k, @@ -1386,7 +1387,7 @@ func flattenHandlerMapping(appHandlerMappings *[]webapps.HandlerMapping) []Handl return []HandlerMappings{} } - var handlerMappings []HandlerMappings + handlerMappings := make([]HandlerMappings, 0, len(*appHandlerMappings)) for _, v := range *appHandlerMappings { handlerMapping := HandlerMappings{ Extension: pointer.From(v.Extension), @@ -1404,7 +1405,7 @@ func flattenVirtualApplications(appVirtualApplications *[]webapps.VirtualApplica return []VirtualApplication{} } - var virtualApplications []VirtualApplication + virtualApplications := make([]VirtualApplication, 0, len(*appVirtualApplications)) for _, v := range *appVirtualApplications { virtualApp := VirtualApplication{ VirtualPath: pointer.From(v.VirtualPath), diff --git a/internal/services/appservice/helpers/fx_strings.go b/internal/services/appservice/helpers/fx_strings.go index 128a5d6ab597..dbb9498ab532 100644 --- a/internal/services/appservice/helpers/fx_strings.go +++ b/internal/services/appservice/helpers/fx_strings.go @@ -281,7 +281,6 @@ func JavaLinuxFxStringBuilder(javaMajorVersion, javaServer, javaServerVersion st default: return pointer.To(fmt.Sprintf("%s|%s-%s", javaServer, javaServerVersion, javaMajorVersion)), nil - } return nil, fmt.Errorf("unsupported combination of `java_version`, `java_server`, and `java_server_version`") } diff --git a/internal/services/appservice/helpers/shared_schema.go b/internal/services/appservice/helpers/shared_schema.go index 5767f6c3bea8..54ea44ad4b0d 100644 --- a/internal/services/appservice/helpers/shared_schema.go +++ b/internal/services/appservice/helpers/shared_schema.go @@ -1478,7 +1478,7 @@ func FlattenIpRestrictions(ipRestrictionsList *[]webapps.IPSecurityRestriction) return []IpRestriction{} } - var ipRestrictions []IpRestriction + ipRestrictions := make([]IpRestriction, 0, len(*ipRestrictionsList)) for _, v := range *ipRestrictionsList { ipRestriction := IpRestriction{} diff --git a/internal/services/appservice/helpers/web_app_slot_schema.go b/internal/services/appservice/helpers/web_app_slot_schema.go index cf7e28851a0e..34a024601fab 100644 --- a/internal/services/appservice/helpers/web_app_slot_schema.go +++ b/internal/services/appservice/helpers/web_app_slot_schema.go @@ -910,7 +910,6 @@ func (s *SiteConfigLinuxWebAppSlot) Flatten(appSiteSlotConfig *webapps.SiteConfi linuxAppStack = decodeApplicationStackLinux(s.LinuxFxVersion) s.ApplicationStack = []ApplicationStackLinux{linuxAppStack} } - } func (s *SiteConfigLinuxWebAppSlot) SetHealthCheckEvictionTime(input map[string]string) { @@ -952,7 +951,6 @@ func (s *SiteConfigLinuxWebAppSlot) DecodeDockerDeprecatedAppStack(input map[str applicationStack = s.ApplicationStack[0] } if !usesDeprecated { - if v, ok := input["DOCKER_REGISTRY_SERVER_URL"]; ok { applicationStack.DockerRegistryUrl = v } @@ -1226,7 +1224,6 @@ func (s *SiteConfigWindowsWebAppSlot) ExpandForUpdate(metadata sdk.ResourceMetaD appSettings["DOCKER_REGISTRY_SERVER_USERNAME"] = winAppStack.DockerRegistryUsername appSettings["DOCKER_REGISTRY_SERVER_PASSWORD"] = winAppStack.DockerRegistryPassword } - } else { expanded.WindowsFxVersion = pointer.To("") } @@ -1415,7 +1412,6 @@ func (s *SiteConfigWindowsWebAppSlot) Flatten(appSiteSlotConfig *webapps.SiteCon winAppStack.CurrentStack = currentStack s.ApplicationStack = []ApplicationStackWindows{winAppStack} - } func (s *SiteConfigWindowsWebAppSlot) SetHealthCheckEvictionTime(input map[string]string) { diff --git a/internal/services/appservice/helpers/windows_web_app_schema.go b/internal/services/appservice/helpers/windows_web_app_schema.go index 1481e907c70f..a3122e6f7aac 100644 --- a/internal/services/appservice/helpers/windows_web_app_schema.go +++ b/internal/services/appservice/helpers/windows_web_app_schema.go @@ -562,9 +562,7 @@ func (s *SiteConfigWindows) ExpandForCreate(appSettings map[string]string) (*web appSettings["DOCKER_REGISTRY_SERVER_URL"] = winAppStack.DockerRegistryUrl appSettings["DOCKER_REGISTRY_SERVER_USERNAME"] = winAppStack.DockerRegistryUsername appSettings["DOCKER_REGISTRY_SERVER_PASSWORD"] = winAppStack.DockerRegistryPassword - } - } else { expanded.WindowsFxVersion = pointer.To("") } @@ -720,7 +718,6 @@ func (s *SiteConfigWindows) ExpandForUpdate(metadata sdk.ResourceMetaData, exist appSettings["DOCKER_REGISTRY_SERVER_USERNAME"] = winAppStack.DockerRegistryUsername appSettings["DOCKER_REGISTRY_SERVER_PASSWORD"] = winAppStack.DockerRegistryPassword } - } else { expanded.WindowsFxVersion = pointer.To("") } diff --git a/internal/services/appservice/linux_function_app_resource.go b/internal/services/appservice/linux_function_app_resource.go index 81b973b683bd..3b2fc06f579e 100644 --- a/internal/services/appservice/linux_function_app_resource.go +++ b/internal/services/appservice/linux_function_app_resource.go @@ -1262,10 +1262,8 @@ func (r LinuxFunctionAppResource) CustomizeDiff() sdk.ResourceFunc { if helpers.PlanIsConsumption(sku.Name) && newValue.(bool) { return fmt.Errorf("`vnet_image_pull_enabled` cannot be enabled on consumption plans") } - } } - } if rd.HasChange("service_plan_id") { currentPlanIdRaw, newPlanIdRaw := rd.GetChange("service_plan_id") @@ -1330,7 +1328,6 @@ func (r LinuxFunctionAppResource) CustomizeDiff() sdk.ResourceFunc { } } } - } return nil }, diff --git a/internal/services/appservice/linux_function_app_slot_resource.go b/internal/services/appservice/linux_function_app_slot_resource.go index b861db1efc81..a3d1e148f3f5 100644 --- a/internal/services/appservice/linux_function_app_slot_resource.go +++ b/internal/services/appservice/linux_function_app_slot_resource.go @@ -444,7 +444,6 @@ func (r LinuxFunctionAppSlotResource) Create() sdk.ResourceFunc { } } } - } // Only send for ElasticPremium sendContentSettings := helpers.PlanIsElastic(planSKU) && !functionAppSlot.ForceDisableContentShare diff --git a/internal/services/appservice/linux_function_app_slot_resource_authv2_test.go b/internal/services/appservice/linux_function_app_slot_resource_authv2_test.go index b9e3bfc35e7d..17a6984146a4 100644 --- a/internal/services/appservice/linux_function_app_slot_resource_authv2_test.go +++ b/internal/services/appservice/linux_function_app_slot_resource_authv2_test.go @@ -276,7 +276,6 @@ resource "azurerm_linux_function_app_slot" "test" { } func (r LinuxFunctionAppSlotResource) authV2AzureActiveDirectoryNoSecretName(data acceptance.TestData, planSku string) string { - return fmt.Sprintf(` provider "azurerm" { features {} diff --git a/internal/services/appservice/linux_web_app_data_source.go b/internal/services/appservice/linux_web_app_data_source.go index ebd55e6779ad..ebdac0f5061e 100644 --- a/internal/services/appservice/linux_web_app_data_source.go +++ b/internal/services/appservice/linux_web_app_data_source.go @@ -416,7 +416,6 @@ func (r LinuxWebAppDataSource) Read() sdk.ResourceFunc { if err := metadata.Encode(&webApp); err != nil { return fmt.Errorf("encoding: %+v", err) } - } return nil diff --git a/internal/services/appservice/linux_web_app_slot_resource.go b/internal/services/appservice/linux_web_app_slot_resource.go index aaac8f9d2565..efba577ba963 100644 --- a/internal/services/appservice/linux_web_app_slot_resource.go +++ b/internal/services/appservice/linux_web_app_slot_resource.go @@ -668,7 +668,6 @@ func (r LinuxWebAppSlotResource) Read() sdk.ResourceFunc { if err := metadata.Encode(&state); err != nil { return fmt.Errorf("encoding: %+v", err) } - } return nil diff --git a/internal/services/appservice/linux_web_app_slot_resource_authv2_test.go b/internal/services/appservice/linux_web_app_slot_resource_authv2_test.go index 8070e540d7d9..4f121662e9f7 100644 --- a/internal/services/appservice/linux_web_app_slot_resource_authv2_test.go +++ b/internal/services/appservice/linux_web_app_slot_resource_authv2_test.go @@ -200,7 +200,6 @@ resource "azurerm_linux_web_app_slot" "test" { } func (r LinuxWebAppSlotResource) authV2AzureActiveDirectoryNoSecretName(data acceptance.TestData) string { - return fmt.Sprintf(` provider "azurerm" { features {} diff --git a/internal/services/appservice/source_control_resource.go b/internal/services/appservice/source_control_resource.go index b2665c7a6595..0b5a613ad476 100644 --- a/internal/services/appservice/source_control_resource.go +++ b/internal/services/appservice/source_control_resource.go @@ -264,7 +264,6 @@ func (r SourceControlResource) Read() sdk.ResourceFunc { GithubActionConfiguration: flattenGitHubActionConfiguration(props.GitHubActionConfiguration), LocalGitSCM: pointer.From(siteConfig.Model.Properties.ScmType) == webapps.ScmTypeLocalGit, } - } return metadata.Encode(&state) diff --git a/internal/services/appservice/validate/static_web_app.go b/internal/services/appservice/validate/static_web_app.go index 9b1b831f8ef0..ee7bb924de4d 100644 --- a/internal/services/appservice/validate/static_web_app.go +++ b/internal/services/appservice/validate/static_web_app.go @@ -4,6 +4,7 @@ package validate import ( + "errors" "fmt" "regexp" ) @@ -21,35 +22,35 @@ func StaticWebAppName(v interface{}, k string) (warnings []string, errors []erro return warnings, errors } -func StaticWebAppPassword(v interface{}, k string) (warnings []string, errors []error) { +func StaticWebAppPassword(v interface{}, k string) (warnings []string, errs []error) { value, ok := v.(string) if !ok { - errors = append(errors, fmt.Errorf("expected %s to be a string", k)) + errs = append(errs, fmt.Errorf("expected %s to be a string", k)) return } if len(value) < 8 { - errors = append(errors, fmt.Errorf("the password should be at least eight characters long.")) + errs = append(errs, errors.New("the password should be at least eight characters long.")) } if matched := regexp.MustCompile(`[!@#$%^&*(),.?":{}|<>]`).Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("the password must contain at least one symbol")) + errs = append(errs, errors.New("the password must contain at least one symbol")) } if matched := regexp.MustCompile(`[a-z]`).Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("the password must contain at least one lower case letter")) + errs = append(errs, errors.New("the password must contain at least one lower case letter")) } if matched := regexp.MustCompile(`[A-Z]`).Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("the password must contain at least one upper case letter")) + errs = append(errs, errors.New("the password must contain at least one upper case letter")) } if matched := regexp.MustCompile(`[0-9]`).Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("the password must contain at least one number")) + errs = append(errs, errors.New("the password must contain at least one number")) } if matched := regexp.MustCompile(`[!@#$%^&*(),.?":{}|<>]`).Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("the password must contain at least one symbol")) + errs = append(errs, errors.New("the password must contain at least one symbol")) } return diff --git a/internal/services/appservice/windows_function_app_resource.go b/internal/services/appservice/windows_function_app_resource.go index bd4cec5f62f4..23d80654ab9f 100644 --- a/internal/services/appservice/windows_function_app_resource.go +++ b/internal/services/appservice/windows_function_app_resource.go @@ -760,7 +760,6 @@ func (r WindowsFunctionAppResource) Read() sdk.ResourceFunc { } if props := model.Properties; props != nil { - state.Enabled = pointer.From(props.Enabled) state.ClientCertMode = string(pointer.From(props.ClientCertMode)) state.ClientCertExclusionPaths = pointer.From(props.ClientCertExclusionPaths) @@ -807,7 +806,6 @@ func (r WindowsFunctionAppResource) Read() sdk.ResourceFunc { if subnetId := pointer.From(props.VirtualNetworkSubnetId); subnetId != "" { state.VirtualNetworkSubnetID = subnetId } - } configResp, err := client.GetConfiguration(ctx, *id) if err != nil { @@ -1284,7 +1282,6 @@ func (r WindowsFunctionAppResource) CustomizeDiff() sdk.ResourceFunc { if helpers.PlanIsConsumption(sku.Name) && newValue.(bool) { return fmt.Errorf("`vnet_image_pull_enabled` cannot be enabled on consumption plans") } - } } } @@ -1394,7 +1391,6 @@ func (m *WindowsFunctionAppModel) unpackWindowsFunctionAppSettings(input *webapp m.SiteConfig[0].ApplicationStack[0].DotNetIsolated = true case "custom": m.SiteConfig[0].ApplicationStack[0].CustomHandler = true - } case "DOCKER_REGISTRY_SERVER_URL": diff --git a/internal/services/appservice/windows_function_app_slot_resource.go b/internal/services/appservice/windows_function_app_slot_resource.go index c470279a8103..3e018738f22d 100644 --- a/internal/services/appservice/windows_function_app_slot_resource.go +++ b/internal/services/appservice/windows_function_app_slot_resource.go @@ -808,7 +808,6 @@ func (r WindowsFunctionAppSlotResource) Read() sdk.ResourceFunc { if subnetId := pointer.From(props.VirtualNetworkSubnetId); subnetId != "" { state.VirtualNetworkSubnetID = subnetId } - } configResp, err := client.GetConfigurationSlot(ctx, *id) diff --git a/internal/services/appservice/windows_web_app_data_source.go b/internal/services/appservice/windows_web_app_data_source.go index 7b1bf589be5d..6c125223d767 100644 --- a/internal/services/appservice/windows_web_app_data_source.go +++ b/internal/services/appservice/windows_web_app_data_source.go @@ -415,7 +415,6 @@ func (d WindowsWebAppDataSource) Read() sdk.ResourceFunc { if err = metadata.Encode(&webApp); err != nil { return fmt.Errorf("encoding: %+v", err) } - } metadata.SetID(id) diff --git a/internal/services/appservice/windows_web_app_resource.go b/internal/services/appservice/windows_web_app_resource.go index efecb558a250..05a337bdf4a6 100644 --- a/internal/services/appservice/windows_web_app_resource.go +++ b/internal/services/appservice/windows_web_app_resource.go @@ -730,7 +730,6 @@ func (r WindowsWebAppResource) Read() sdk.ResourceFunc { if err := metadata.Encode(&state); err != nil { return fmt.Errorf("encoding: %+v", err) } - } } diff --git a/internal/services/appservice/windows_web_app_slot_resource.go b/internal/services/appservice/windows_web_app_slot_resource.go index 13bbe909e404..df7353e05883 100644 --- a/internal/services/appservice/windows_web_app_slot_resource.go +++ b/internal/services/appservice/windows_web_app_slot_resource.go @@ -704,7 +704,6 @@ func (r WindowsWebAppSlotResource) Read() sdk.ResourceFunc { if err := metadata.Encode(&state); err != nil { return fmt.Errorf("encoding: %+v", err) } - } return nil diff --git a/internal/services/arckubernetes/arc_kubernetes_cluster_extension_resource.go b/internal/services/arckubernetes/arc_kubernetes_cluster_extension_resource.go index 3e8eef9f1da1..05e4544ab10b 100644 --- a/internal/services/arckubernetes/arc_kubernetes_cluster_extension_resource.go +++ b/internal/services/arckubernetes/arc_kubernetes_cluster_extension_resource.go @@ -149,7 +149,6 @@ func (r ArcKubernetesClusterExtensionResource) Arguments() map[string]*pluginsdk ValidateFunc: validation.StringIsNotEmpty, }, } - } func (r ArcKubernetesClusterExtensionResource) Attributes() map[string]*pluginsdk.Schema { diff --git a/internal/services/attestation/validate/stored_attestation_policy_base64.go b/internal/services/attestation/validate/stored_attestation_policy_base64.go index d32ede0aacc8..018c253b1067 100644 --- a/internal/services/attestation/validate/stored_attestation_policy_base64.go +++ b/internal/services/attestation/validate/stored_attestation_policy_base64.go @@ -6,38 +6,39 @@ package validate import ( "encoding/base64" "encoding/json" + "errors" "fmt" "strings" "github.com/jackofallops/kermit/sdk/attestation/2022-08-01/attestation" ) -func ContainsABase64UriEncodedJWTOfAStoredAttestationPolicy(value interface{}, key string) (warnings []string, errors []error) { +func ContainsABase64UriEncodedJWTOfAStoredAttestationPolicy(value interface{}, key string) (warnings []string, errs []error) { v, ok := value.(string) if !ok { - errors = append(errors, fmt.Errorf("%q cannot be an empty string", key)) + errs = append(errs, fmt.Errorf("%q cannot be an empty string", key)) return } split := strings.Split(v, ".") if len(split) != 3 { - errors = append(errors, fmt.Errorf("expected %q to be a JWT with 3 segments but got %d segments", key, len(split))) + errs = append(errs, fmt.Errorf("expected %q to be a JWT with 3 segments but got %d segments", key, len(split))) return } // decode the JWT into a StoredAttestationPolicy object decodedJwtSegment, err := base64.RawURLEncoding.DecodeString(split[1]) if err != nil { - errors = append(errors, fmt.Errorf("base64-decoding the first JWT Segment %q: %+v", split[1], err)) + errs = append(errs, fmt.Errorf("base64-decoding the first JWT Segment %q: %+v", split[1], err)) return } var result attestation.StoredAttestationPolicy if err := json.Unmarshal(decodedJwtSegment, &result); err != nil { - errors = append(errors, fmt.Errorf("unmarshaling into StoredAttestationPolicy - please check your policy against the documentation at https://learn.microsoft.com/azure/attestation/author-sign-policy: %+v", err)) + errs = append(errs, fmt.Errorf("unmarshaling into StoredAttestationPolicy - please check your policy against the documentation at https://learn.microsoft.com/azure/attestation/author-sign-policy: %+v", err)) return } if result.AttestationPolicy == nil { - errors = append(errors, fmt.Errorf("expected a key for AttestationPolicy but didn't get one - see https://learn.microsoft.com/azure/attestation/author-sign-policy for more information")) + errs = append(errs, errors.New("expected a key for AttestationPolicy but didn't get one - see https://learn.microsoft.com/azure/attestation/author-sign-policy for more information")) return } diff --git a/internal/services/authorization/parse/id_scopedroleassignment.go b/internal/services/authorization/parse/id_scopedroleassignment.go index 4e88161321cc..527bd9500f9f 100644 --- a/internal/services/authorization/parse/id_scopedroleassignment.go +++ b/internal/services/authorization/parse/id_scopedroleassignment.go @@ -56,7 +56,7 @@ func (id ScopedRoleAssignmentId) String() string { } if id.TenantId != "" { - components = append(components, fmt.Sprintf("Tenant ID: %s", id.TenantId)) + components = append(components, "Tenant ID: "+id.TenantId) } return fmt.Sprintf("Scoped Role Assignment (%s)", strings.Join(components, "\n")) diff --git a/internal/services/authorization/parse/role_assignment.go b/internal/services/authorization/parse/role_assignment.go index fe964ca072bd..33ded67aabe1 100644 --- a/internal/services/authorization/parse/role_assignment.go +++ b/internal/services/authorization/parse/role_assignment.go @@ -4,6 +4,7 @@ package parse import ( + "errors" "fmt" "strings" @@ -27,30 +28,30 @@ type RoleAssignmentId struct { func NewRoleAssignmentID(subscriptionId, resourceGroup, resourceProvider, resourceScope, managementGroup, name, tenantId, subscriptionAlias string, isSubLevel bool, isSubAliasLevel bool) (*RoleAssignmentId, error) { if subscriptionId == "" && resourceGroup == "" && managementGroup == "" && !isSubLevel && !isSubAliasLevel { - return nil, fmt.Errorf("one of subscriptionId, resourceGroup, managementGroup, isSubscriptionLevel or isSubscriptionAliasLevel must be provided") + return nil, errors.New("one of subscriptionId, resourceGroup, managementGroup, isSubscriptionLevel or isSubscriptionAliasLevel must be provided") } if managementGroup != "" { if subscriptionId != "" || resourceGroup != "" || isSubLevel { - return nil, fmt.Errorf("cannot provide subscriptionId, resourceGroup or isSubscriptionLevel when managementGroup is provided") + return nil, errors.New("cannot provide subscriptionId, resourceGroup or isSubscriptionLevel when managementGroup is provided") } } if isSubLevel { if subscriptionId != "" || resourceGroup != "" || managementGroup != "" { - return nil, fmt.Errorf("cannot provide subscriptionId, resourceGroup or managementGroup when isSubscriptionLevel is provided") + return nil, errors.New("cannot provide subscriptionId, resourceGroup or managementGroup when isSubscriptionLevel is provided") } } if isSubAliasLevel { if subscriptionId != "" || resourceGroup != "" || managementGroup != "" { - return nil, fmt.Errorf("cannot provide subscriptionId, resourceGroup or managementGroup when isSubscriptionAliasLevel is provided") + return nil, errors.New("cannot provide subscriptionId, resourceGroup or managementGroup when isSubscriptionAliasLevel is provided") } } if resourceGroup != "" { if subscriptionId == "" { - return nil, fmt.Errorf("subscriptionId must not be empty when resourceGroup is provided") + return nil, errors.New("subscriptionId must not be empty when resourceGroup is provided") } } @@ -185,7 +186,7 @@ func RoleAssignmentID(input string) (*RoleAssignmentId, error) { return nil, fmt.Errorf("could not parse Role Assignment ID %q for Management Group", input) } if idParts[1] == "" { - return nil, fmt.Errorf("ID was missing a value for the roleAssignments element") + return nil, errors.New("ID was missing a value for the roleAssignments element") } roleAssignmentId.Name = idParts[1] roleAssignmentId.ManagementGroup = strings.TrimPrefix(idParts[0], "/providers/Microsoft.Management/managementGroups/") @@ -195,14 +196,14 @@ func RoleAssignmentID(input string) (*RoleAssignmentId, error) { return nil, fmt.Errorf("could not parse Role Assignment ID %q for Resource Provider", input) } if idParts[1] == "" { - return nil, fmt.Errorf("ID was missing a value for the roleAssignments element") + return nil, errors.New("ID was missing a value for the roleAssignments element") } roleAssignmentId.Name = idParts[1] roleAssignmentId.ResourceProvider = strings.TrimPrefix(idParts[0], "/providers/") case strings.HasPrefix(input, "/providers/Microsoft.Authorization/roleAssignments"): name := strings.TrimPrefix(input, "/providers/Microsoft.Authorization/roleAssignments/") if name == "" { - return nil, fmt.Errorf("ID was missing a value for the roleAssignments element") + return nil, errors.New("ID was missing a value for the roleAssignments element") } roleAssignmentId.Name = name default: diff --git a/internal/services/authorization/parse/role_assignment_test.go b/internal/services/authorization/parse/role_assignment_test.go index 85897ac11835..874265cd49c7 100644 --- a/internal/services/authorization/parse/role_assignment_test.go +++ b/internal/services/authorization/parse/role_assignment_test.go @@ -332,6 +332,5 @@ func TestRoleAssignmentID(t *testing.T) { if actual.SubscriptionAlias != v.Expected.SubscriptionAlias { t.Fatalf("Expected %q but got %q for Role Assignment SubscriptionAlias", v.Expected.SubscriptionAlias, actual.SubscriptionAlias) } - } } diff --git a/internal/services/authorization/role_assignment_resource.go b/internal/services/authorization/role_assignment_resource.go index f80586267fe1..40ebcee8028c 100644 --- a/internal/services/authorization/role_assignment_resource.go +++ b/internal/services/authorization/role_assignment_resource.go @@ -327,7 +327,6 @@ func resourceArmRoleAssignmentRead(d *pluginsdk.ResourceData, meta interface{}) if roleResp.Model != nil && roleResp.Model.Properties != nil { d.Set("role_definition_name", pointer.From(roleResp.Model.Properties.RoleName)) } - } } diff --git a/internal/services/authorization/role_management_policy.go b/internal/services/authorization/role_management_policy.go index ea8a00596692..75d80995e4d9 100644 --- a/internal/services/authorization/role_management_policy.go +++ b/internal/services/authorization/role_management_policy.go @@ -216,7 +216,6 @@ func buildRoleManagementPolicyForUpdate(metadata *sdk.ResourceMetaData, rolePoli metadata.ResourceData.HasChange("activation_rules.0.require_ticket_info") { if enablementEndUserAssignmentBase, ok := existingRules["Enablement_EndUser_Assignment"]; ok { if enablementEndUserAssignment, ok := enablementEndUserAssignmentBase.(rolemanagementpolicies.RoleManagementPolicyEnablementRule); ok { - enabledRules := make([]rolemanagementpolicies.EnablementRules, 0) if len(model.ActivationRules) == 1 { if model.ActivationRules[0].RequireMultiFactorAuth { diff --git a/internal/services/authorization/role_management_policy_data_source.go b/internal/services/authorization/role_management_policy_data_source.go index 6c6524ebb99e..215014d70a62 100644 --- a/internal/services/authorization/role_management_policy_data_source.go +++ b/internal/services/authorization/role_management_policy_data_source.go @@ -450,7 +450,6 @@ func (r RoleManagementPolicyDataSource) Read() sdk.ResourceFunc { case "Expiration_EndUser_Assignment": state.ActivationRules[0].MaximumDuration = pointer.From(rule.MaximumDuration) - } } case rolemanagementpolicies.RoleManagementPolicyNotificationRule: diff --git a/internal/services/authorization/role_management_policy_resource.go b/internal/services/authorization/role_management_policy_resource.go index ba77eb1f769b..2daa1a985cc1 100644 --- a/internal/services/authorization/role_management_policy_resource.go +++ b/internal/services/authorization/role_management_policy_resource.go @@ -540,7 +540,6 @@ func (r RoleManagementPolicyResource) Read() sdk.ResourceFunc { case "Expiration_EndUser_Assignment": state.ActivationRules[0].MaximumDuration = pointer.From(rule.MaximumDuration) - } } case rolemanagementpolicies.RoleManagementPolicyNotificationRule: diff --git a/internal/services/automanage/arc_machine_automanage_configuration_assignment_resource.go b/internal/services/automanage/arc_machine_automanage_configuration_assignment_resource.go index a01ad3e88df6..29ea8b437634 100644 --- a/internal/services/automanage/arc_machine_automanage_configuration_assignment_resource.go +++ b/internal/services/automanage/arc_machine_automanage_configuration_assignment_resource.go @@ -87,7 +87,7 @@ func (v ArcMachineConfigurationAssignment) Create() sdk.ResourceFunc { properties := configurationprofilehcrpassignments.ConfigurationProfileAssignment{ Properties: &configurationprofilehcrpassignments.ConfigurationProfileAssignmentProperties{ - ConfigurationProfile: pointer.FromString(configurationId.ID()), + ConfigurationProfile: pointer.To(configurationId.ID()), }, } diff --git a/internal/services/automation/automation_account_resource_test.go b/internal/services/automation/automation_account_resource_test.go index 322089b95089..b1b74194b48d 100644 --- a/internal/services/automation/automation_account_resource_test.go +++ b/internal/services/automation/automation_account_resource_test.go @@ -390,7 +390,6 @@ resource "azurerm_key_vault_key" "test" { } func (a AutomationAccountResource) encryption_none(data acceptance.TestData) string { - return fmt.Sprintf(` %s @@ -417,7 +416,6 @@ resource "azurerm_role_assignment" "test" { } func (a AutomationAccountResource) encryption_basic(data acceptance.TestData) string { - return fmt.Sprintf(` @@ -449,7 +447,6 @@ resource "azurerm_automation_account" "test" { } func (a AutomationAccountResource) encryption_userIdentity(data acceptance.TestData) string { - return fmt.Sprintf(` diff --git a/internal/services/automation/automation_connection_service_principal_resource.go b/internal/services/automation/automation_connection_service_principal_resource.go index 87dd3b6e4069..66fb91522f87 100644 --- a/internal/services/automation/automation_connection_service_principal_resource.go +++ b/internal/services/automation/automation_connection_service_principal_resource.go @@ -164,7 +164,6 @@ func resourceAutomationConnectionServicePrincipalRead(d *pluginsdk.ResourceData, if model := resp.Model; model != nil { if props := model.Properties; props != nil { - description := "" if props.Description != nil { description = *props.Description diff --git a/internal/services/automation/automation_connection_type_resource.go b/internal/services/automation/automation_connection_type_resource.go index ba390585e0f1..554c5ccf060d 100644 --- a/internal/services/automation/automation_connection_type_resource.go +++ b/internal/services/automation/automation_connection_type_resource.go @@ -27,11 +27,11 @@ type Field struct { } type AutomationConnectionTypeModel struct { - ResourceGroup string `json:"resource_group" tfschema:"resource_group_name"` + ResourceGroup string `json:"resource_group" tfschema:"resource_group_name"` AutomationAccountName string `json:"automation_account_name" tfschema:"automation_account_name"` - Name string `json:"name" tfschema:"name"` - IsGlobal bool `json:"is_global" tfschema:"is_global"` - Field []Field `json:"field" tfschema:"field"` + Name string `json:"name" tfschema:"name"` + IsGlobal bool `json:"is_global" tfschema:"is_global"` + Field []Field `json:"field" tfschema:"field"` } type AutomationConnectionTypeResource struct{} diff --git a/internal/services/automation/automation_runbook_resource.go b/internal/services/automation/automation_runbook_resource.go index 4ed2210440e9..69e4951848ad 100644 --- a/internal/services/automation/automation_runbook_resource.go +++ b/internal/services/automation/automation_runbook_resource.go @@ -26,7 +26,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func contentLinkSchema(isDraft bool) *pluginsdk.Schema { @@ -309,22 +308,16 @@ func resourceAutomationRunbookCreateUpdate(d *pluginsdk.ResourceData, meta inter // for existing runbook, if only job_schedule field updated, then skip update runbook if d.IsNewResource() || d.HasChangeExcept("job_schedule") { - location := azure.NormalizeLocation(d.Get("location").(string)) t := d.Get("tags").(map[string]interface{}) - runbookType := runbook.RunbookTypeEnum(d.Get("runbook_type").(string)) - logProgress := d.Get("log_progress").(bool) - logVerbose := d.Get("log_verbose").(bool) - description := d.Get("description").(string) - parameters := runbook.RunbookCreateOrUpdateParameters{ Properties: runbook.RunbookCreateOrUpdateProperties{ - LogVerbose: &logVerbose, - LogProgress: &logProgress, - RunbookType: runbookType, - Description: &description, - LogActivityTrace: utils.Int64(int64(d.Get("log_activity_trace_level").(int))), + LogVerbose: pointer.To(d.Get("log_verbose").(bool)), + LogProgress: pointer.To(d.Get("log_progress").(bool)), + RunbookType: runbook.RunbookTypeEnum(d.Get("runbook_type").(string)), + Description: pointer.To(d.Get("description").(string)), + LogActivityTrace: pointer.To(int64(d.Get("log_activity_trace_level").(int))), }, Location: &location, @@ -540,23 +533,24 @@ func expandDraft(inputs []interface{}) *runbook.RunbookDraft { var res runbook.RunbookDraft res.DraftContentLink = expandContentLink(input["content_link"].([]interface{})) - res.InEdit = utils.Bool(input["edit_mode_enabled"].(bool)) + res.InEdit = pointer.To(input["edit_mode_enabled"].(bool)) parameter := map[string]runbook.RunbookParameter{} for _, iparam := range input["parameters"].([]interface{}) { param := iparam.(map[string]interface{}) key := param["key"].(string) parameter[key] = runbook.RunbookParameter{ - Type: utils.String(param["type"].(string)), - IsMandatory: utils.Bool(param["mandatory"].(bool)), - Position: utils.Int64(int64(param["position"].(int))), - DefaultValue: utils.String(param["default_value"].(string)), + Type: pointer.To(param["type"].(string)), + IsMandatory: pointer.To(param["mandatory"].(bool)), + Position: pointer.To(int64(param["position"].(int))), + DefaultValue: pointer.To(param["default_value"].(string)), } } res.Parameters = ¶meter - var types []string - for _, v := range input["output_types"].([]interface{}) { + typesInput := input["output_types"].([]interface{}) + types := make([]string, 0, len(typesInput)) + for _, v := range typesInput { types = append(types, v.(string)) } diff --git a/internal/services/automation/automation_schedule_resource.go b/internal/services/automation/automation_schedule_resource.go index 5be6025d6e77..e8a0e366c487 100644 --- a/internal/services/automation/automation_schedule_resource.go +++ b/internal/services/automation/automation_schedule_resource.go @@ -270,7 +270,6 @@ func resourceAutomationScheduleCreate(d *pluginsdk.ResourceData, meta interface{ // only pay attention to interval if frequency is not OneTime, and default it to 1 if not set if parameters.Properties.Frequency != schedule.ScheduleFrequencyOneTime { - var interval interface{} interval = 1 if v, ok := d.GetOk("interval"); ok { @@ -306,7 +305,6 @@ func resourceAutomationScheduleUpdate(d *pluginsdk.ResourceData, meta interface{ existing, err := client.Get(ctx, id) if err != nil { return fmt.Errorf("checking for presence of existing %s: %v", id, err) - } if existing.Model == nil || existing.Model.Properties == nil { diff --git a/internal/services/automation/automation_software_update_configuration_resource.go b/internal/services/automation/automation_software_update_configuration_resource.go index 8179f51c2aab..6655565a0142 100644 --- a/internal/services/automation/automation_software_update_configuration_resource.go +++ b/internal/services/automation/automation_software_update_configuration_resource.go @@ -1076,7 +1076,6 @@ func (m SoftwareUpdateConfigurationResource) Update() sdk.ResourceFunc { } else { target.NonAzureQueries = &[]softwareupdateconfiguration.NonAzureQueryProperties{} } - } else { target.AzureQueries = &[]softwareupdateconfiguration.AzureQueryProperties{} target.NonAzureQueries = &[]softwareupdateconfiguration.NonAzureQueryProperties{} diff --git a/internal/services/automation/automation_webhook_resource.go b/internal/services/automation/automation_webhook_resource.go index 6eee362eb2cd..83891ebc8517 100644 --- a/internal/services/automation/automation_webhook_resource.go +++ b/internal/services/automation/automation_webhook_resource.go @@ -206,7 +206,6 @@ func resourceAutomationWebhookRead(d *pluginsdk.ResourceData, meta interface{}) if model := resp.Model; model != nil { if props := model.Properties; props != nil { - d.Set("expiry_time", props.ExpiryTime) d.Set("enabled", props.IsEnabled) diff --git a/internal/services/automation/helper/automation_job_schedule.go b/internal/services/automation/helper/automation_job_schedule.go index c0822a249fa2..7017891ed3cf 100644 --- a/internal/services/automation/helper/automation_job_schedule.go +++ b/internal/services/automation/helper/automation_job_schedule.go @@ -119,7 +119,7 @@ func ResourceAutomationJobScheduleDigest(v interface{}) string { } buf.WriteString(fmt.Sprintf("%s-%s-", scheduleName, runOn)) - var keys []string + keys := make([]string, 0, len(paramString)) for k := range paramString { // params key will be returned as title-cased even created with lower-case keys = append(keys, k) diff --git a/internal/services/azurestackhci/stack_hci_marketplace_gallery_image_resource.go b/internal/services/azurestackhci/stack_hci_marketplace_gallery_image_resource.go index cb5070480c25..517cc7ceb217 100644 --- a/internal/services/azurestackhci/stack_hci_marketplace_gallery_image_resource.go +++ b/internal/services/azurestackhci/stack_hci_marketplace_gallery_image_resource.go @@ -248,7 +248,6 @@ func (r StackHCIMarketplaceGalleryImageResource) Read() sdk.ResourceFunc { schema.Version = pointer.From(props.Version.Name) } } - } return metadata.Encode(&schema) }, diff --git a/internal/services/batch/batch_account_resource.go b/internal/services/batch/batch_account_resource.go index 1e7c7dda327c..a9815fa71bea 100644 --- a/internal/services/batch/batch_account_resource.go +++ b/internal/services/batch/batch_account_resource.go @@ -354,7 +354,6 @@ func resourceBatchAccountRead(d *pluginsdk.ResourceData, meta interface{}) error } if props := model.Properties; props != nil { - d.Set("account_endpoint", props.AccountEndpoint) if autoStorage := props.AutoStorage; autoStorage != nil { d.Set("storage_account_id", autoStorage.StorageAccountId) @@ -632,7 +631,6 @@ func flattenBatchAccountEndpointAccessProfile(input *batchaccount.EndpointAccess } ipRules = append(ipRules, flattenedIpRule) } - } return []interface{}{ diff --git a/internal/services/batch/batch_pool.go b/internal/services/batch/batch_pool.go index 4c28790fa4a8..9d92649354de 100644 --- a/internal/services/batch/batch_pool.go +++ b/internal/services/batch/batch_pool.go @@ -542,17 +542,17 @@ func expandBatchPoolContainerRegistry(ref map[string]interface{}) (*pool.Contain containerRegistry := pool.ContainerRegistry{} if v := ref["registry_server"]; v != nil && v != "" { - containerRegistry.RegistryServer = pointer.FromString(v.(string)) + containerRegistry.RegistryServer = pointer.To(v.(string)) } if v := ref["user_name"]; v != nil && v != "" { - containerRegistry.Username = pointer.FromString(v.(string)) + containerRegistry.Username = pointer.To(v.(string)) } if v := ref["password"]; v != nil && v != "" { - containerRegistry.Password = pointer.FromString(v.(string)) + containerRegistry.Password = pointer.To(v.(string)) } if v := ref["user_assigned_identity_id"]; v != nil && v != "" { containerRegistry.IdentityReference = &pool.ComputeNodeIdentityReference{ - ResourceId: pointer.FromString(v.(string)), + ResourceId: pointer.To(v.(string)), } } @@ -561,8 +561,7 @@ func expandBatchPoolContainerRegistry(ref map[string]interface{}) (*pool.Contain // ExpandBatchPoolCertificateReferences expands Batch pool certificate references func ExpandBatchPoolCertificateReferences(list []interface{}) (*[]pool.CertificateReference, error) { - var result []pool.CertificateReference - + result := make([]pool.CertificateReference, 0, len(list)) for _, tempItem := range list { item := tempItem.(map[string]interface{}) certificateReference, err := expandBatchPoolCertificateReference(item) @@ -920,8 +919,8 @@ func expandBatchPoolDataDisks(list []interface{}) *[]pool.DataDisk { if len(list) == 0 || list[0] == nil { return nil } - var result []pool.DataDisk + result := make([]pool.DataDisk, 0, len(list)) for _, tempItem := range list { item := tempItem.(map[string]interface{}) result = append(result, expandBatchPoolDataDisk(item)) diff --git a/internal/services/batch/client/client.go b/internal/services/batch/client/client.go index 05072a4ba227..d29db7765c70 100644 --- a/internal/services/batch/client/client.go +++ b/internal/services/batch/client/client.go @@ -69,7 +69,7 @@ func (r *Client) JobClient(ctx context.Context, accountId batchaccount.BatchAcco endpoint := "" if account.Model != nil && account.Model.Properties != nil { - endpoint = fmt.Sprintf("https://%s", *account.Model.Properties.AccountEndpoint) + endpoint = "https://" + *account.Model.Properties.AccountEndpoint } if endpoint == "" { return nil, fmt.Errorf("retrieving %s: `properties.AccountEndpoint` was empty", accountId) diff --git a/internal/services/blueprints/blueprint_assignment_resource.go b/internal/services/blueprints/blueprint_assignment_resource.go index 22468778658b..a640b3256856 100644 --- a/internal/services/blueprints/blueprint_assignment_resource.go +++ b/internal/services/blueprints/blueprint_assignment_resource.go @@ -4,6 +4,7 @@ package blueprints import ( + "errors" "fmt" "log" "time" @@ -321,7 +322,7 @@ func resourceBlueprintAssignmentDelete(d *pluginsdk.ResourceData, meta interface deadline, ok := ctx.Deadline() if !ok { - return fmt.Errorf("internal-error: context had no deadline") + return errors.New("internal-error: context had no deadline") } stateConf := &pluginsdk.StateChangeConf{ Pending: []string{ diff --git a/internal/services/blueprints/blueprint_assingment.go b/internal/services/blueprints/blueprint_assingment.go index edb94c75eafe..f2aa660c5855 100644 --- a/internal/services/blueprints/blueprint_assingment.go +++ b/internal/services/blueprints/blueprint_assingment.go @@ -6,6 +6,7 @@ package blueprints import ( "context" "encoding/json" + "errors" "fmt" "github.com/hashicorp/go-azure-helpers/lang/response" @@ -20,12 +21,12 @@ func blueprintAssignmentCreateStateRefreshFunc(ctx context.Context, client *assi return nil, "", fmt.Errorf("unable to retrieve Blueprint Assignment %s: %+v", id.String(), err) } if resp.Model == nil || resp.Model.Properties.ProvisioningState == nil { - return resp, "nil", fmt.Errorf("Blueprint Assignment Model or ProvisioningState is nil") + return resp, "nil", errors.New("Blueprint Assignment Model or ProvisioningState is nil") } state := *resp.Model.Properties.ProvisioningState if state == assignment.AssignmentProvisioningStateFailed { - return resp, string(state), fmt.Errorf("Blueprint Assignment provisioning entered a Failed state.") + return resp, string(state), errors.New("Blueprint Assignment provisioning entered a Failed state.") } return resp, string(state), nil @@ -44,7 +45,7 @@ func blueprintAssignmentDeleteStateRefreshFunc(ctx context.Context, client *assi } if resp.Model == nil || resp.Model.Properties.ProvisioningState == nil { - return resp, "nil", fmt.Errorf("Blueprint Assignment Model or ProvisioningState is nil") + return resp, "nil", errors.New("Blueprint Assignment Model or ProvisioningState is nil") } return resp, string(*resp.Model.Properties.ProvisioningState), nil } diff --git a/internal/services/bot/bot_connection_resource.go b/internal/services/bot/bot_connection_resource.go index bce5f9e7fdfa..7f6ca9c9387f 100644 --- a/internal/services/bot/bot_connection_resource.go +++ b/internal/services/bot/bot_connection_resource.go @@ -4,11 +4,13 @@ package bot import ( + "errors" "fmt" "log" "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" @@ -119,7 +121,6 @@ func resourceArmBotConnectionCreate(d *pluginsdk.ResourceData, meta interface{}) serviceProviderName := d.Get("service_provider_name").(string) var serviceProviderId *string - var availableProviders []string serviceProviders, err := client.ListServiceProviders(ctx) if err != nil { @@ -127,8 +128,10 @@ func resourceArmBotConnectionCreate(d *pluginsdk.ResourceData, meta interface{}) } if serviceProviders.Value == nil { - return fmt.Errorf("no service providers were returned from the Azure API") + return errors.New("no service providers were returned from the Azure API") } + + availableProviders := make([]string, 0, len(*serviceProviders.Value)) for _, provider := range *serviceProviders.Value { if provider.Properties == nil || provider.Properties.ServiceProviderName == nil { continue @@ -148,12 +151,12 @@ func resourceArmBotConnectionCreate(d *pluginsdk.ResourceData, meta interface{}) connection := botservice.ConnectionSetting{ Properties: &botservice.ConnectionSettingProperties{ ServiceProviderID: serviceProviderId, - ClientID: utils.String(d.Get("client_id").(string)), - ClientSecret: utils.String(d.Get("client_secret").(string)), - Scopes: utils.String(d.Get("scopes").(string)), + ClientID: pointer.To(d.Get("client_id").(string)), + ClientSecret: pointer.To(d.Get("client_secret").(string)), + Scopes: pointer.To(d.Get("scopes").(string)), }, Kind: botservice.KindBot, - Location: utils.String(d.Get("location").(string)), + Location: pointer.To(d.Get("location").(string)), } if v, ok := d.GetOk("parameters"); ok { diff --git a/internal/services/bot/validate/bot.go b/internal/services/bot/validate/bot.go index 535698f32fa8..1610743e6d4f 100644 --- a/internal/services/bot/validate/bot.go +++ b/internal/services/bot/validate/bot.go @@ -4,19 +4,19 @@ package validate import ( - "fmt" + "errors" "strings" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) func BotMSTeamsCallingWebHook() pluginsdk.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { + return func(i interface{}, k string) (warnings []string, errs []error) { value := i.(string) if !strings.HasPrefix(value, "https://") || !strings.HasSuffix(value, "/") { - errors = append(errors, fmt.Errorf("invalid `calling_web_hook`, must start with `https://` and end with `/`")) + errs = append(errs, errors.New("invalid `calling_web_hook`, must start with `https://` and end with `/`")) } - return warnings, errors + return warnings, errs } } diff --git a/internal/services/cdn/cdn_frontdoor_route_resource.go b/internal/services/cdn/cdn_frontdoor_route_resource.go index 8ad50013de09..18cfab538697 100644 --- a/internal/services/cdn/cdn_frontdoor_route_resource.go +++ b/internal/services/cdn/cdn_frontdoor_route_resource.go @@ -225,9 +225,6 @@ func resourceCdnFrontDoorRouteCreate(d *pluginsdk.ResourceData, meta interface{} return tf.ImportAsExistsError("azurerm_cdn_frontdoor_route", id.ID()) } - var origins []interface{} - var originGroup *cdn.ResourceReference - protocolsRaw := d.Get("supported_protocols").(*pluginsdk.Set).List() originGroupRaw := d.Get("cdn_frontdoor_origin_group_id").(string) ruleSetIdsRaw := d.Get("cdn_frontdoor_rule_set_ids").(*pluginsdk.Set).List() @@ -262,6 +259,7 @@ func resourceCdnFrontDoorRouteCreate(d *pluginsdk.ResourceData, meta interface{} } } + var originGroup *cdn.ResourceReference if originGroupRaw != "" { id, err := parse.FrontDoorOriginGroupID(originGroupRaw) if err != nil { @@ -308,6 +306,7 @@ func resourceCdnFrontDoorRouteCreate(d *pluginsdk.ResourceData, meta interface{} // NOTE: These are not sent to the API, they are only here so Terraform // can provision/destroy the resources in the correct order. + origins := make([]string, 0, len(originsRaw)) for _, origin := range originsRaw { id, err := parse.FrontDoorOriginID(origin.(string)) if err != nil { diff --git a/internal/services/cdn/validate/cdn.go b/internal/services/cdn/validate/cdn.go index aa0ee6f09034..b27e9d19f39b 100644 --- a/internal/services/cdn/validate/cdn.go +++ b/internal/services/cdn/validate/cdn.go @@ -4,7 +4,7 @@ package validate import ( - "fmt" + "errors" "regexp" "strings" @@ -39,14 +39,14 @@ func RuleActionUrlRedirectQueryString() pluginsdk.SchemaValidateFunc { re := regexp.MustCompile("^[?&]") if re.MatchString(querystring) { - return nil, []error{fmt.Errorf("the Url Query String must not start with a question mark or ampersand")} + return nil, []error{errors.New("the Url Query String must not start with a question mark or ampersand")} } kvre := regexp.MustCompile("^[^?&]+=[^?&]+$") kvs := strings.Split(querystring, "&") for _, kv := range kvs { if len(kv) > 0 && !kvre.MatchString(kv) { - return nil, []error{fmt.Errorf("the Url Query String must be in = format and separated by an ampersand")} + return nil, []error{errors.New("the Url Query String must be in = format and separated by an ampersand")} } } diff --git a/internal/services/chaosstudio/client/client_gen.go b/internal/services/chaosstudio/client/client_gen.go index dee9ebe8c7d7..1c1efb7001ad 100644 --- a/internal/services/chaosstudio/client/client_gen.go +++ b/internal/services/chaosstudio/client/client_gen.go @@ -13,7 +13,6 @@ type AutoClient struct { } func NewClient(o *common.ClientOptions) (*AutoClient, error) { - v20231101Client, err := chaosstudioV20231101.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { o.Configure(c, o.Authorizers.ResourceManager) }) diff --git a/internal/services/chaosstudio/custompollers/chaos_studio_experiment_poller.go b/internal/services/chaosstudio/custompollers/chaos_studio_experiment_poller.go index 58e58fceff51..965b576910db 100644 --- a/internal/services/chaosstudio/custompollers/chaos_studio_experiment_poller.go +++ b/internal/services/chaosstudio/custompollers/chaos_studio_experiment_poller.go @@ -63,7 +63,6 @@ func (p chaosStudioExperimentPoller) Poll(ctx context.Context) (*pollers.PollRes var op operationResult contentType := resp.HttpResponse.Header.Get("Content-Type") if strings.Contains(strings.ToLower(contentType), "application/json") { - if err = json.Unmarshal(respBody, &op); err != nil { return nil, fmt.Errorf("unmarshalling response body: %+v", err) } diff --git a/internal/services/cognitive/ai_services_resource.go b/internal/services/cognitive/ai_services_resource.go index 5210730855fc..6d7cb2ecbe07 100644 --- a/internal/services/cognitive/ai_services_resource.go +++ b/internal/services/cognitive/ai_services_resource.go @@ -502,7 +502,7 @@ func (AzureAIServicesResource) Update() sdk.ResourceFunc { } if metadata.ResourceData.HasChange("custom_subdomain_name") { - props.Properties.CustomSubDomainName = pointer.FromString(model.CustomSubdomainName) + props.Properties.CustomSubDomainName = pointer.To(model.CustomSubdomainName) } if metadata.ResourceData.HasChange("fqdns") { @@ -637,7 +637,6 @@ func expandAzureAIServicesCustomerManagedKey(input []AzureAIServicesCustomerMana encryption.KeyVaultProperties.KeyVaultUri = pointer.To(hsmKyId.BaseUri()) } return encryption, nil - } func flattenAzureAIServicesCustomerManagedKey(input *cognitiveservicesaccounts.Encryption, env environments.Environment) ([]AzureAIServicesCustomerManagedKey, error) { diff --git a/internal/services/cognitive/client/client.go b/internal/services/cognitive/client/client.go index 4ff11ddd38c8..e9692f5de8ff 100644 --- a/internal/services/cognitive/client/client.go +++ b/internal/services/cognitive/client/client.go @@ -17,7 +17,6 @@ type Client struct { } func NewClient(o *common.ClientOptions) (*Client, error) { - accountsClient, err := cognitiveservicesaccounts.NewCognitiveServicesAccountsClientWithBaseURI(o.Environment.ResourceManager) if err != nil { return nil, fmt.Errorf("building Accounts client: %+v", err) diff --git a/internal/services/cognitive/cognitive_deployment_resource.go b/internal/services/cognitive/cognitive_deployment_resource.go index 25e3d83efe52..40ecfcc8b9dc 100644 --- a/internal/services/cognitive/cognitive_deployment_resource.go +++ b/internal/services/cognitive/cognitive_deployment_resource.go @@ -321,7 +321,6 @@ func (r CognitiveDeploymentResource) Read() sdk.ResourceFunc { } if properties := model.Properties; properties != nil { - state.Model = flattenDeploymentModelModel(properties.Model) if v := properties.RaiPolicyName; v != nil { diff --git a/internal/services/communication/email_service_domain_resource.go b/internal/services/communication/email_service_domain_resource.go index 6a782eb30bc9..5e663730042f 100644 --- a/internal/services/communication/email_service_domain_resource.go +++ b/internal/services/communication/email_service_domain_resource.go @@ -250,7 +250,6 @@ func (EmailCommunicationServiceDomainResource) Read() sdk.ResourceFunc { if props.UserEngagementTracking != nil { state.UserEngagementTrackingEnabled = *props.UserEngagementTracking == domains.UserEngagementTrackingEnabled - } domainVerificationRecords := EmailDomainVerificationRecords{} diff --git a/internal/services/compute/disk_encryption_set_resource.go b/internal/services/compute/disk_encryption_set_resource.go index d17eb7ce66d5..8b5d1a0f1cfe 100644 --- a/internal/services/compute/disk_encryption_set_resource.go +++ b/internal/services/compute/disk_encryption_set_resource.go @@ -337,7 +337,6 @@ func resourceDiskEncryptionSetRead(d *pluginsdk.ResourceData, meta interface{}) } } } - } encryptionType := string(diskencryptionsets.DiskEncryptionSetTypeEncryptionAtRestWithCustomerKey) diff --git a/internal/services/compute/image_resource_test.go b/internal/services/compute/image_resource_test.go index 1c9841b1941e..697b04ef8283 100644 --- a/internal/services/compute/image_resource_test.go +++ b/internal/services/compute/image_resource_test.go @@ -242,7 +242,6 @@ func (ImageResource) generalizeVirtualMachine(data acceptance.TestData) func(con if configs := props.IPConfigurations; configs != nil { for _, config := range *props.IPConfigurations { if configProps := config.Properties; configProps != nil { - if configProps.PublicIPAddress == nil { continue } diff --git a/internal/services/compute/linux_virtual_machine_resource.go b/internal/services/compute/linux_virtual_machine_resource.go index a92e1ec8bd34..3c4cde6ea2c6 100644 --- a/internal/services/compute/linux_virtual_machine_resource.go +++ b/internal/services/compute/linux_virtual_machine_resource.go @@ -994,7 +994,6 @@ func resourceLinuxVirtualMachineRead(d *pluginsdk.ResourceData, meta interface{} if err := d.Set("source_image_reference", flattenSourceImageReference(profile.ImageReference, storageImageId != "")); err != nil { return fmt.Errorf("setting `source_image_reference`: %+v", err) } - } if scheduleProfile := props.ScheduledEventsProfile; scheduleProfile != nil { diff --git a/internal/services/compute/linux_virtual_machine_scale_set_resource_other_test.go b/internal/services/compute/linux_virtual_machine_scale_set_resource_other_test.go index 8f0d9b12c484..cd053a455bbb 100644 --- a/internal/services/compute/linux_virtual_machine_scale_set_resource_other_test.go +++ b/internal/services/compute/linux_virtual_machine_scale_set_resource_other_test.go @@ -836,7 +836,6 @@ func TestAccLinuxVirtualMachineScaleSet_otherCancelRollingUpgrades(t *testing.T) } return nil - }, data.ResourceName), ), }, diff --git a/internal/services/compute/managed_disk_resource.go b/internal/services/compute/managed_disk_resource.go index 184b61150f92..4db1c1b8933d 100644 --- a/internal/services/compute/managed_disk_resource.go +++ b/internal/services/compute/managed_disk_resource.go @@ -913,7 +913,6 @@ func resourceManagedDiskUpdate(d *pluginsdk.ResourceData, meta interface{}) erro options.SkipShutdown = pointer.To(false) if err := virtualMachinesClient.PowerOffThenPoll(ctx, *virtualMachineId, options); err != nil { return fmt.Errorf("sending Power Off to %s: %+v", virtualMachineId, err) - } log.Printf("[DEBUG] Shut Down %s", virtualMachineId) diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set.go b/internal/services/compute/orchestrated_virtual_machine_scale_set.go index 906ffd52286f..238d9724a5ab 100644 --- a/internal/services/compute/orchestrated_virtual_machine_scale_set.go +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set.go @@ -1626,7 +1626,6 @@ func FlattenOrchestratedVirtualMachineScaleSetIPConfiguration(input virtualmachi applicationGatewayBackendAddressPoolIds = flattenSubResourcesToIDs(props.ApplicationGatewayBackendAddressPools) applicationSecurityGroupIds = flattenSubResourcesToIDs(props.ApplicationSecurityGroups) loadBalancerBackendAddressPoolIds = flattenSubResourcesToIDs(props.LoadBalancerBackendAddressPools) - } return map[string]interface{}{ @@ -1686,7 +1685,6 @@ func FlattenOrchestratedVirtualMachineScaleSetPublicIPAddress(input virtualmachi if input.Sku != nil && input.Sku.Name != nil && input.Sku.Tier != nil { sku = flattenOrchestratedVirtualMachineScaleSetPublicIPSku(input.Sku) } - } return map[string]interface{}{ @@ -1855,7 +1853,6 @@ func FlattenOrchestratedVirtualMachineScaleSetNetworkInterface(input *[]virtualm ipConfigurations = append(ipConfigurations, config) } } - } results = append(results, map[string]interface{}{ @@ -2025,7 +2022,6 @@ func FlattenOrchestratedVirtualMachineScaleSetScheduledEventsProfile(input *virt } func FlattenOrchestratedVirtualMachineScaleSetPriorityMixPolicy(input *virtualmachinescalesets.PriorityMixPolicy) []interface{} { - baseRegularPriorityCount := int64(0) if input != nil && input.BaseRegularPriorityCount != nil { baseRegularPriorityCount = *input.BaseRegularPriorityCount diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set_data_source.go b/internal/services/compute/orchestrated_virtual_machine_scale_set_data_source.go index da69a19e9d6c..3ef81fe0bb6b 100644 --- a/internal/services/compute/orchestrated_virtual_machine_scale_set_data_source.go +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set_data_source.go @@ -175,7 +175,6 @@ func (r OrchestratedVirtualMachineScaleSetDataSource) Read() sdk.ResourceFunc { orchestratedVMSS.NetworkInterface = flattenVirtualMachineScaleSetNetworkInterface(nwProfile.NetworkInterfaceConfigurations) } } - } } diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set_resource_test.go b/internal/services/compute/orchestrated_virtual_machine_scale_set_resource_test.go index c2fa2f8dbd01..7f3b3597a90d 100644 --- a/internal/services/compute/orchestrated_virtual_machine_scale_set_resource_test.go +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set_resource_test.go @@ -652,7 +652,6 @@ func (OrchestratedVirtualMachineScaleSetResource) hasApplicationGateway(ctx cont } } } - } return fmt.Errorf("application gateway configuration was missing") diff --git a/internal/services/compute/shared_image_data_source.go b/internal/services/compute/shared_image_data_source.go index bfefcf48ba10..7672ec6592d0 100644 --- a/internal/services/compute/shared_image_data_source.go +++ b/internal/services/compute/shared_image_data_source.go @@ -244,7 +244,6 @@ func dataSourceSharedImageRead(d *pluginsdk.ResourceData, meta interface{}) erro } return tags.FlattenAndSet(d, model.Tags) - } return nil } diff --git a/internal/services/compute/shared_image_version_resource.go b/internal/services/compute/shared_image_version_resource.go index 20dba27c41b1..16e2aef5da06 100644 --- a/internal/services/compute/shared_image_version_resource.go +++ b/internal/services/compute/shared_image_version_resource.go @@ -416,10 +416,8 @@ func resourceSharedImageVersionRead(d *pluginsdk.ResourceData, meta interface{}) if safetyProfile := props.SafetyProfile; safetyProfile != nil { d.Set("deletion_of_replicated_locations_enabled", pointer.From(safetyProfile.AllowDeletionOfReplicatedLocations)) } - } return tags.FlattenAndSet(d, model.Tags) - } return nil } diff --git a/internal/services/compute/shared_image_versions_data_source.go b/internal/services/compute/shared_image_versions_data_source.go index b07180fc9ae5..7394071bd613 100644 --- a/internal/services/compute/shared_image_versions_data_source.go +++ b/internal/services/compute/shared_image_versions_data_source.go @@ -157,7 +157,6 @@ func flattenSharedImageVersions(input []galleryimageversions.GalleryImageVersion } } } - } if found { diff --git a/internal/services/compute/virtual_machine_run_command_resource.go b/internal/services/compute/virtual_machine_run_command_resource.go index 0a0601739c98..0d183ad63721 100644 --- a/internal/services/compute/virtual_machine_run_command_resource.go +++ b/internal/services/compute/virtual_machine_run_command_resource.go @@ -594,7 +594,6 @@ func expandVirtualMachineRunCommandInputParameter(input []VirtualMachineRunComma Value: v.Value, } output = append(output, parameter) - } return &output } @@ -611,7 +610,6 @@ func flattenVirtualMachineRunCommandInputParameter(input *[]virtualmachineruncom Value: v.Value, } output = append(output, parameter) - } return output diff --git a/internal/services/compute/windows_virtual_machine_scale_set_resource.go b/internal/services/compute/windows_virtual_machine_scale_set_resource.go index ed16aa9679ff..029a40be5405 100644 --- a/internal/services/compute/windows_virtual_machine_scale_set_resource.go +++ b/internal/services/compute/windows_virtual_machine_scale_set_resource.go @@ -443,7 +443,6 @@ func resourceWindowsVirtualMachineScaleSetCreate(d *pluginsdk.ResourceData, meta } props.Properties.ScaleInPolicy = scaleInPolicy - } if v, ok := d.GetOk("scale_in"); ok { if v := ExpandVirtualMachineScaleSetScaleInPolicy(v.([]interface{})); v != nil { diff --git a/internal/services/compute/windows_virtual_machine_scale_set_resource_other_test.go b/internal/services/compute/windows_virtual_machine_scale_set_resource_other_test.go index 90df1695130b..e26f8cdd599b 100644 --- a/internal/services/compute/windows_virtual_machine_scale_set_resource_other_test.go +++ b/internal/services/compute/windows_virtual_machine_scale_set_resource_other_test.go @@ -979,7 +979,6 @@ func TestAccWindowsVirtualMachineScaleSet_otherCancelRollingUpgrades(t *testing. } return nil - }, data.ResourceName), ), }, diff --git a/internal/services/containerapps/container_app_environment_custom_domain_resource.go b/internal/services/containerapps/container_app_environment_custom_domain_resource.go index 284986695201..de09cff95a0b 100644 --- a/internal/services/containerapps/container_app_environment_custom_domain_resource.go +++ b/internal/services/containerapps/container_app_environment_custom_domain_resource.go @@ -241,7 +241,6 @@ func (r ContainerAppEnvironmentCustomDomainResource) Update() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - lawClient := metadata.Client.LogAnalytics.SharedKeyWorkspacesClient client := metadata.Client.ContainerApps.ManagedEnvironmentClient subscriptionId := metadata.Client.Account.SubscriptionId diff --git a/internal/services/containerapps/container_app_environment_resource_test.go b/internal/services/containerapps/container_app_environment_resource_test.go index 870d5a814d8d..e97718d18073 100644 --- a/internal/services/containerapps/container_app_environment_resource_test.go +++ b/internal/services/containerapps/container_app_environment_resource_test.go @@ -355,7 +355,6 @@ resource "azurerm_container_app_environment" "test" { } } `, r.templateVNet(data), data.RandomInteger) - } func (r ContainerAppEnvironmentResource) completeMultipleWorkloadProfiles(data acceptance.TestData) string { @@ -403,7 +402,6 @@ resource "azurerm_container_app_environment" "test" { } } `, r.templateVNet(data), data.RandomInteger) - } func (r ContainerAppEnvironmentResource) completeZoneRedundant(data acceptance.TestData) string { diff --git a/internal/services/containerapps/container_app_environment_storage_resource_test.go b/internal/services/containerapps/container_app_environment_storage_resource_test.go index 804c925137c7..2d7e8d0d9015 100644 --- a/internal/services/containerapps/container_app_environment_storage_resource_test.go +++ b/internal/services/containerapps/container_app_environment_storage_resource_test.go @@ -89,7 +89,6 @@ func (r ContainerAppEnvironmentStorageResource) Exists(ctx context.Context, clie } return pointer.To(true), nil - } func (r ContainerAppEnvironmentStorageResource) basic(data acceptance.TestData) string { diff --git a/internal/services/containerapps/container_app_resource.go b/internal/services/containerapps/container_app_resource.go index 2757148bae7b..1b77862144b1 100644 --- a/internal/services/containerapps/container_app_resource.go +++ b/internal/services/containerapps/container_app_resource.go @@ -390,7 +390,6 @@ func (r ContainerAppResource) Update() sdk.ResourceFunc { if metadata.ResourceData.HasChange("dapr") { model.Properties.Configuration.Dapr = helpers.ExpandContainerAppDapr(state.Dapr) - } if metadata.ResourceData.HasChange("template") { @@ -418,7 +417,6 @@ func (r ContainerAppResource) Update() sdk.ResourceFunc { return err } model.Identity = pointer.To(identity.LegacySystemAndUserAssignedMap(*ident)) - } if metadata.ResourceData.HasChange("workload_profile_name") { diff --git a/internal/services/containerapps/helpers/container_apps.go b/internal/services/containerapps/helpers/container_apps.go index 9f3fee51dbe9..4dd958e3576c 100644 --- a/internal/services/containerapps/helpers/container_apps.go +++ b/internal/services/containerapps/helpers/container_apps.go @@ -2697,7 +2697,6 @@ func ExpandFormerContainerSecrets(metadata sdk.ResourceMetaData) *[]containerapp secretsRaw, _ := metadata.ResourceData.GetChange("secret") result := make([]containerapps.Secret, 0) if secrets, ok := secretsRaw.([]interface{}); ok { - for _, secret := range secrets { if v, ok := secret.(map[string]interface{}); ok { result = append(result, containerapps.Secret{ diff --git a/internal/services/containers/client/client_gen.go b/internal/services/containers/client/client_gen.go index 9ef90ffa8ae1..a9fbb47b247a 100644 --- a/internal/services/containers/client/client_gen.go +++ b/internal/services/containers/client/client_gen.go @@ -15,7 +15,6 @@ type AutoClient struct { } func NewClient(o *common.ClientOptions) (*AutoClient, error) { - v20230302PreviewClient, err := containerserviceV20230302Preview.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { o.Configure(c, o.Authorizers.ResourceManager) }) diff --git a/internal/services/containers/container_group_resource.go b/internal/services/containers/container_group_resource.go index 5531f70965e9..1de6cec83d4b 100644 --- a/internal/services/containers/container_group_resource.go +++ b/internal/services/containers/container_group_resource.go @@ -750,7 +750,7 @@ func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) e } containerGroup := containerinstance.ContainerGroup{ - Name: pointer.FromString(id.ContainerGroupName), + Name: pointer.To(id.ContainerGroupName), Location: &location, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), Properties: containerinstance.ContainerGroupPropertiesProperties{ @@ -978,7 +978,7 @@ func resourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) err d.Set("dns_name_label_reuse_policy", containerinstance.DnsNameLabelReusePolicyUnsecure) } } else { - d.Set("dns_name_label_reuse_policy", pointer.FromString(string(containerinstance.DnsNameLabelReusePolicyUnsecure))) + d.Set("dns_name_label_reuse_policy", pointer.To(string(containerinstance.DnsNameLabelReusePolicyUnsecure))) } restartPolicy := "" @@ -1111,7 +1111,7 @@ func expandContainerGroupInitContainers(d *pluginsdk.ResourceData, addedEmptyDir container := containerinstance.InitContainerDefinition{ Name: name, Properties: containerinstance.InitContainerPropertiesDefinition{ - Image: pointer.FromString(image), + Image: pointer.To(image), SecurityContext: expandContainerSecurityContext(data["security"].([]interface{})), }, } @@ -1274,7 +1274,6 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma if v := containerinstance.GpuSku(v["sku"].(string)); v != "" { container.Properties.Resources.Limits.Gpu.Sku = v } - } } @@ -1426,7 +1425,7 @@ func expandContainerEnvironmentVariables(input interface{}, secure bool) *[]cont for k, v := range envVars { ev := containerinstance.EnvironmentVariable{ Name: k, - SecureValue: pointer.FromString(v.(string)), + SecureValue: pointer.To(v.(string)), } output = append(output, ev) @@ -1435,7 +1434,7 @@ func expandContainerEnvironmentVariables(input interface{}, secure bool) *[]cont for k, v := range envVars { ev := containerinstance.EnvironmentVariable{ Name: k, - Value: pointer.FromString(v.(string)), + Value: pointer.To(v.(string)), } output = append(output, ev) @@ -1460,13 +1459,13 @@ func expandContainerImageRegistryCredentials(d *pluginsdk.ResourceData) *[]conta imageRegistryCredential.Server = v.(string) } if v := credConfig["username"]; v != nil && v != "" { - imageRegistryCredential.Username = pointer.FromString(v.(string)) + imageRegistryCredential.Username = pointer.To(v.(string)) } if v := credConfig["password"]; v != nil && v != "" { - imageRegistryCredential.Password = pointer.FromString(v.(string)) + imageRegistryCredential.Password = pointer.To(v.(string)) } if v := credConfig["user_assigned_identity_id"]; v != nil && v != "" { - imageRegistryCredential.Identity = pointer.FromString(v.(string)) + imageRegistryCredential.Identity = pointer.To(v.(string)) } output = append(output, imageRegistryCredential) @@ -1539,7 +1538,7 @@ func expandSingleContainerVolume(input interface{}) (*[]containerinstance.Volume ShareName: shareName, ReadOnly: pointer.FromBool(readOnly), StorageAccountName: storageAccountName, - StorageAccountKey: pointer.FromString(storageAccountKey), + StorageAccountKey: pointer.To(storageAccountKey), } } @@ -1558,10 +1557,10 @@ func expandGitRepoVolume(input []interface{}) *containerinstance.GitRepoVolume { Repository: v["url"].(string), } if directory := v["directory"].(string); directory != "" { - gitRepoVolume.Directory = pointer.FromString(directory) + gitRepoVolume.Directory = pointer.To(directory) } if revision := v["revision"].(string); revision != "" { - gitRepoVolume.Revision = pointer.FromString(revision) + gitRepoVolume.Revision = pointer.To(revision) } return gitRepoVolume } @@ -1636,7 +1635,7 @@ func expandContainerProbe(input interface{}) *containerinstance.ContainerProbe { httpGetScheme := containerinstance.Scheme(scheme) probe.HTTPGet = &containerinstance.ContainerHTTPGet{ - Path: pointer.FromString(path), + Path: pointer.To(path), Port: int64(port), Scheme: &httpGetScheme, HTTPHeaders: expandContainerProbeHttpHeaders(x["http_headers"].(map[string]interface{})), @@ -1655,8 +1654,8 @@ func expandContainerProbeHttpHeaders(input map[string]interface{}) *[]containeri headers := []containerinstance.HTTPHeader{} for k, v := range input { header := containerinstance.HTTPHeader{ - Name: pointer.FromString(k), - Value: pointer.FromString(v.(string)), + Name: pointer.To(k), + Value: pointer.To(v.(string)), } headers = append(headers, header) } @@ -2165,8 +2164,8 @@ func expandContainerGroupDnsConfig(input interface{}) *containerinstance.DnsConf } return &containerinstance.DnsConfiguration{ - Options: pointer.FromString(strings.Join(options, " ")), - SearchDomains: pointer.FromString(strings.Join(searchDomains, " ")), + Options: pointer.To(strings.Join(options, " ")), + SearchDomains: pointer.To(strings.Join(searchDomains, " ")), NameServers: nameservers, } } diff --git a/internal/services/containers/container_registry_agent_pool_resource.go b/internal/services/containers/container_registry_agent_pool_resource.go index b0c0533aa12e..2b6e6a140634 100644 --- a/internal/services/containers/container_registry_agent_pool_resource.go +++ b/internal/services/containers/container_registry_agent_pool_resource.go @@ -133,7 +133,6 @@ func resourceContainerRegistryAgentPoolCreate(d *pluginsdk.ResourceData, meta in if err := client.CreateThenPoll(ctx, id, parameters); err != nil { return fmt.Errorf("creating %s: %+v", id, err) - } d.SetId(id.ID()) diff --git a/internal/services/containers/container_registry_resource.go b/internal/services/containers/container_registry_resource.go index 66c420f1d4d8..6e83d72960da 100644 --- a/internal/services/containers/container_registry_resource.go +++ b/internal/services/containers/container_registry_resource.go @@ -661,7 +661,6 @@ func resourceContainerRegistryRead(d *pluginsdk.ResourceData, meta interface{}) } d.Set("quarantine_policy_enabled", flattenQuarantinePolicy(props.Policies)) d.Set("export_policy_enabled", flattenExportPolicy(props.Policies)) - } if *props.AdminUserEnabled { diff --git a/internal/services/containers/container_registry_resource_test.go b/internal/services/containers/container_registry_resource_test.go index a10553b0827e..498d19578230 100644 --- a/internal/services/containers/container_registry_resource_test.go +++ b/internal/services/containers/container_registry_resource_test.go @@ -455,7 +455,6 @@ resource "azurerm_container_registry" "test" { sku = "%s" } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, sku) - } func (r ContainerRegistryResource) requiresImport(data acceptance.TestData, sku string) string { diff --git a/internal/services/containers/container_registry_task_resource.go b/internal/services/containers/container_registry_task_resource.go index 280a60cca427..22bd95074df2 100644 --- a/internal/services/containers/container_registry_task_resource.go +++ b/internal/services/containers/container_registry_task_resource.go @@ -861,7 +861,6 @@ func (r ContainerRegistryTaskResource) Delete() sdk.ResourceFunc { } if err := client.DeleteThenPoll(ctx, *id); err != nil { - return fmt.Errorf("deleting %s: %+v", id, err) } diff --git a/internal/services/containers/kubernetes_cluster_data_source.go b/internal/services/containers/kubernetes_cluster_data_source.go index 3696cb2b8392..ba85e92d3e0d 100644 --- a/internal/services/containers/kubernetes_cluster_data_source.go +++ b/internal/services/containers/kubernetes_cluster_data_source.go @@ -786,7 +786,6 @@ func dataSourceKubernetesCluster() *pluginsdk.Resource { }, }, } - } return resource diff --git a/internal/services/containers/kubernetes_cluster_other_resource_test.go b/internal/services/containers/kubernetes_cluster_other_resource_test.go index 87dc81598c03..d8680ee1be02 100644 --- a/internal/services/containers/kubernetes_cluster_other_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_other_resource_test.go @@ -1694,7 +1694,6 @@ resource "azurerm_kubernetes_cluster" "test" { } func (KubernetesClusterResource) linuxProfileConfig(data acceptance.TestData, keyData string) string { - return fmt.Sprintf(` provider "azurerm" { features {} @@ -3605,7 +3604,6 @@ resource "azurerm_kubernetes_cluster" "test" { } func (KubernetesClusterResource) customCATrustCertificates(data acceptance.TestData, certsList []string) string { - certsString := "" if certsList != nil { diff --git a/internal/services/containers/kubernetes_cluster_resource.go b/internal/services/containers/kubernetes_cluster_resource.go index 497a1be4fcbe..cbd23a719b70 100644 --- a/internal/services/containers/kubernetes_cluster_resource.go +++ b/internal/services/containers/kubernetes_cluster_resource.go @@ -4355,7 +4355,6 @@ func expandKubernetesClusterServiceMeshProfile(input []interface{}, existing *ma istioIngressGatewaysList := make([]managedclusters.IstioIngressGateway, 0) if raw["internal_ingress_gateway_enabled"] != nil { - ingressGatewayElementInternal := managedclusters.IstioIngressGateway{ Enabled: raw["internal_ingress_gateway_enabled"].(bool), Mode: managedclusters.IstioIngressGatewayModeInternal, @@ -4365,7 +4364,6 @@ func expandKubernetesClusterServiceMeshProfile(input []interface{}, existing *ma } if raw["external_ingress_gateway_enabled"] != nil { - ingressGatewayElementExternal := managedclusters.IstioIngressGateway{ Enabled: raw["external_ingress_gateway_enabled"].(bool), Mode: managedclusters.IstioIngressGatewayModeExternal, @@ -4490,9 +4488,7 @@ func flattenKubernetesClusterAzureServiceMeshProfile(input *managedclusters.Serv } if (input.Istio.Components.IngressGateways != nil) && len(*input.Istio.Components.IngressGateways) > 0 { - for _, value := range *input.Istio.Components.IngressGateways { - mode := value.Mode enabled := value.Enabled @@ -4533,7 +4529,6 @@ func flattenKubernetesClusterServiceMeshProfileCertificateAuthority(certificateA "key_object_name": pointer.From(certificateAuthority.Plugin.KeyObjectName), }, } - } func flattenKubernetesClusterAzureMonitorProfile(input *managedclusters.ManagedClusterAzureMonitorProfile) []interface{} { diff --git a/internal/services/containers/kubernetes_cluster_scaling_resource_test.go b/internal/services/containers/kubernetes_cluster_scaling_resource_test.go index cc1428357b88..490790e79f4c 100644 --- a/internal/services/containers/kubernetes_cluster_scaling_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_scaling_resource_test.go @@ -97,7 +97,6 @@ func TestAccKubernetesCluster_updateVmSizeAfterFailureWithTempAndDefault(t *test }, data.ImportStep("default_node_pool.0.temporary_name_for_rotation"), }) - } func TestAccKubernetesCluster_updateVmSizeAfterFailureWithTempWithoutDefault(t *testing.T) { diff --git a/internal/services/containers/kubernetes_cluster_trusted_access_role_binding_resource_gen.go b/internal/services/containers/kubernetes_cluster_trusted_access_role_binding_resource_gen.go index 9be04b2010e5..ba15b3b880cb 100644 --- a/internal/services/containers/kubernetes_cluster_trusted_access_role_binding_resource_gen.go +++ b/internal/services/containers/kubernetes_cluster_trusted_access_role_binding_resource_gen.go @@ -202,7 +202,6 @@ func (r KubernetesClusterTrustedAccessRoleBindingResource) Update() sdk.Resource } func (r KubernetesClusterTrustedAccessRoleBindingResource) mapKubernetesClusterTrustedAccessRoleBindingResourceSchemaToTrustedAccessRoleBinding(input KubernetesClusterTrustedAccessRoleBindingResourceSchema, output *trustedaccess.TrustedAccessRoleBinding) error { - if err := r.mapKubernetesClusterTrustedAccessRoleBindingResourceSchemaToTrustedAccessRoleBindingProperties(input, &output.Properties); err != nil { return fmt.Errorf("mapping Schema to SDK Field %q / Model %q: %+v", "TrustedAccessRoleBindingProperties", "Properties", err) } @@ -211,7 +210,6 @@ func (r KubernetesClusterTrustedAccessRoleBindingResource) mapKubernetesClusterT } func (r KubernetesClusterTrustedAccessRoleBindingResource) mapTrustedAccessRoleBindingToKubernetesClusterTrustedAccessRoleBindingResourceSchema(input trustedaccess.TrustedAccessRoleBinding, output *KubernetesClusterTrustedAccessRoleBindingResourceSchema) error { - if err := r.mapTrustedAccessRoleBindingPropertiesToKubernetesClusterTrustedAccessRoleBindingResourceSchema(input.Properties, output); err != nil { return fmt.Errorf("mapping SDK Field %q / Model %q to Schema: %+v", "TrustedAccessRoleBindingProperties", "Properties", err) } @@ -220,7 +218,6 @@ func (r KubernetesClusterTrustedAccessRoleBindingResource) mapTrustedAccessRoleB } func (r KubernetesClusterTrustedAccessRoleBindingResource) mapKubernetesClusterTrustedAccessRoleBindingResourceSchemaToTrustedAccessRoleBindingProperties(input KubernetesClusterTrustedAccessRoleBindingResourceSchema, output *trustedaccess.TrustedAccessRoleBindingProperties) error { - roles := make([]string, 0) for _, v := range input.Roles { roles = append(roles, v) @@ -232,7 +229,6 @@ func (r KubernetesClusterTrustedAccessRoleBindingResource) mapKubernetesClusterT } func (r KubernetesClusterTrustedAccessRoleBindingResource) mapTrustedAccessRoleBindingPropertiesToKubernetesClusterTrustedAccessRoleBindingResourceSchema(input trustedaccess.TrustedAccessRoleBindingProperties, output *KubernetesClusterTrustedAccessRoleBindingResourceSchema) error { - roles := make([]string, 0) for _, v := range input.Roles { roles = append(roles, v) diff --git a/internal/services/containers/kubernetes_fleet_member_resource_gen.go b/internal/services/containers/kubernetes_fleet_member_resource_gen.go index aad9e9c797b6..df504f591bb8 100644 --- a/internal/services/containers/kubernetes_fleet_member_resource_gen.go +++ b/internal/services/containers/kubernetes_fleet_member_resource_gen.go @@ -192,7 +192,6 @@ func (r KubernetesFleetMemberResource) Update() sdk.ResourceFunc { } func (r KubernetesFleetMemberResource) mapKubernetesFleetMemberResourceSchemaToFleetMember(input KubernetesFleetMemberResourceSchema, output *fleetmembers.FleetMember) error { - if output.Properties == nil { output.Properties = &fleetmembers.FleetMemberProperties{} } @@ -204,7 +203,6 @@ func (r KubernetesFleetMemberResource) mapKubernetesFleetMemberResourceSchemaToF } func (r KubernetesFleetMemberResource) mapFleetMemberToKubernetesFleetMemberResourceSchema(input fleetmembers.FleetMember, output *KubernetesFleetMemberResourceSchema) error { - if input.Properties == nil { input.Properties = &fleetmembers.FleetMemberProperties{} } @@ -228,7 +226,6 @@ func (r KubernetesFleetMemberResource) mapFleetMemberPropertiesToKubernetesFleet } func (r KubernetesFleetMemberResource) mapKubernetesFleetMemberResourceSchemaToFleetMemberUpdate(input KubernetesFleetMemberResourceSchema, output *fleetmembers.FleetMemberUpdate) error { - if output.Properties == nil { output.Properties = &fleetmembers.FleetMemberUpdateProperties{} } @@ -240,7 +237,6 @@ func (r KubernetesFleetMemberResource) mapKubernetesFleetMemberResourceSchemaToF } func (r KubernetesFleetMemberResource) mapFleetMemberUpdateToKubernetesFleetMemberResourceSchema(input fleetmembers.FleetMemberUpdate, output *KubernetesFleetMemberResourceSchema) error { - if input.Properties == nil { input.Properties = &fleetmembers.FleetMemberUpdateProperties{} } diff --git a/internal/services/containers/kubernetes_fleet_update_run_resource.go b/internal/services/containers/kubernetes_fleet_update_run_resource.go index 16f3e34c91e5..514356f35c78 100644 --- a/internal/services/containers/kubernetes_fleet_update_run_resource.go +++ b/internal/services/containers/kubernetes_fleet_update_run_resource.go @@ -422,7 +422,6 @@ func flattenKubernetesFleetUpdateRunStage(input []updateruns.UpdateStage) []Kube }) } return output - } func flattenKubernetesFleetUpdateRunGroup(input *[]updateruns.UpdateGroup) []KubernetesFleetUpdateRunResourceUpdateGroupSchema { diff --git a/internal/services/containers/kubernetes_fleet_update_strategy_resource.go b/internal/services/containers/kubernetes_fleet_update_strategy_resource.go index 845a62614ca1..9c2899a2b798 100644 --- a/internal/services/containers/kubernetes_fleet_update_strategy_resource.go +++ b/internal/services/containers/kubernetes_fleet_update_strategy_resource.go @@ -269,7 +269,6 @@ func flattenKubernetesFleetUpdateStrategyStage(input []fleetupdatestrategies.Upd }) } return output - } func flattenKubernetesFleetUpdateStrategyGroup(input *[]fleetupdatestrategies.UpdateGroup) []KubernetesFleetUpdateStrategyResourceUpdateGroupSchema { diff --git a/internal/services/cosmos/common/indexing_policy.go b/internal/services/cosmos/common/indexing_policy.go index a634b23cb47b..9ae353952ba4 100644 --- a/internal/services/cosmos/common/indexing_policy.go +++ b/internal/services/cosmos/common/indexing_policy.go @@ -17,8 +17,7 @@ func expandAzureRmCosmosDBIndexingPolicyIncludedPaths(input []interface{}) *[]co return nil } - var includedPaths []cosmosdb.IncludedPath - + includedPaths := make([]cosmosdb.IncludedPath, 0, len(input)) for _, v := range input { includedPath := v.(map[string]interface{}) path := cosmosdb.IncludedPath{ @@ -36,8 +35,7 @@ func expandAzureRmCosmosDBIndexingPolicyExcludedPaths(input []interface{}) *[]co return nil } - var paths []cosmosdb.ExcludedPath - + paths := make([]cosmosdb.ExcludedPath, 0, len(input)) for _, v := range input { block := v.(map[string]interface{}) paths = append(paths, cosmosdb.ExcludedPath{ diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index faa92326f1e6..c794c74c6864 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -2280,10 +2280,10 @@ func prepareCapabilities(capabilities interface{}) *[]cosmosdb.Capability { for _, v := range capabilities.(*pluginsdk.Set).List() { m := v.(map[string]interface{}) if c, ok := m["name"].(string); ok { - cap := cosmosdb.Capability{ + capability := cosmosdb.Capability{ Name: pointer.To(c), } - output = append(output, cap) + output = append(output, capability) } } return &output diff --git a/internal/services/cosmos/cosmosdb_gremlin_graph_resource.go b/internal/services/cosmos/cosmosdb_gremlin_graph_resource.go index ad78f94d1aa0..bade709d6a2d 100644 --- a/internal/services/cosmos/cosmosdb_gremlin_graph_resource.go +++ b/internal/services/cosmos/cosmosdb_gremlin_graph_resource.go @@ -336,7 +336,6 @@ func resourceCosmosDbGremlinGraphUpdate(d *pluginsdk.ResourceData, meta interfac return fmt.Errorf("setting Throughput for Cosmos Gremlin Graph %q (Account: %q, Database: %q): %+v - "+ "If the graph has not been created with an initial throughput, you cannot configure it later", id.GraphName, id.DatabaseAccountName, id.GremlinDatabaseName, err) } - } return resourceCosmosDbGremlinGraphRead(d, meta) diff --git a/internal/services/cosmos/cosmosdb_mongo_role_definition_resource.go b/internal/services/cosmos/cosmosdb_mongo_role_definition_resource.go index e62977abf7cf..8a9b64395204 100644 --- a/internal/services/cosmos/cosmosdb_mongo_role_definition_resource.go +++ b/internal/services/cosmos/cosmosdb_mongo_role_definition_resource.go @@ -292,8 +292,7 @@ func expandPrivilege(input []Privilege) *[]mongorbacs.Privilege { return nil } - var result []mongorbacs.Privilege - + result := make([]mongorbacs.Privilege, 0, len(input)) for _, v := range input { output := mongorbacs.Privilege{ Actions: pointer.To(v.Actions), @@ -307,11 +306,11 @@ func expandPrivilege(input []Privilege) *[]mongorbacs.Privilege { } func flattenPrivilege(input *[]mongorbacs.Privilege) []Privilege { - var result []Privilege if input == nil { - return result + return []Privilege{} } + result := make([]Privilege, 0, len(*input)) for _, input := range *input { privilege := Privilege{ Actions: pointer.From(input.Actions), @@ -362,8 +361,7 @@ func expandInheritedRoles(input []string, dbName string) *[]mongorbacs.Role { return nil } - var result []mongorbacs.Role - + result := make([]mongorbacs.Role, 0, len(input)) for _, v := range input { inheritedRole := mongorbacs.Role{ Db: pointer.To(dbName), @@ -377,11 +375,11 @@ func expandInheritedRoles(input []string, dbName string) *[]mongorbacs.Role { } func flattenInheritedRoles(input *[]mongorbacs.Role) []string { - var result []string if input == nil { - return result + return []string{} } + result := make([]string, 0, len(*input)) for _, v := range *input { result = append(result, pointer.From(v.Role)) } diff --git a/internal/services/cosmos/cosmosdb_postgresql_cluster_resource.go b/internal/services/cosmos/cosmosdb_postgresql_cluster_resource.go index 0ae63b0c5e6e..ec09a165d5d7 100644 --- a/internal/services/cosmos/cosmosdb_postgresql_cluster_resource.go +++ b/internal/services/cosmos/cosmosdb_postgresql_cluster_resource.go @@ -661,12 +661,11 @@ func flattenMaintenanceWindow(input *clusters.MaintenanceWindow) []MaintenanceWi } func flattenServerNames(input *[]clusters.ServerNameItem) []ServerNameItem { - var output []ServerNameItem - if input == nil { - return output + return []ServerNameItem{} } + output := make([]ServerNameItem, 0, len(*input)) for _, v := range *input { output = append(output, ServerNameItem{ FullyQualifiedDomainName: *v.FullyQualifiedDomainName, diff --git a/internal/services/cosmos/cosmosdb_sql_container_resource.go b/internal/services/cosmos/cosmosdb_sql_container_resource.go index d0793ffe2014..fde4e134c2df 100644 --- a/internal/services/cosmos/cosmosdb_sql_container_resource.go +++ b/internal/services/cosmos/cosmosdb_sql_container_resource.go @@ -310,7 +310,6 @@ func resourceCosmosDbSQLContainerUpdate(d *pluginsdk.ResourceData, meta interfac if err != nil { return fmt.Errorf("setting Throughput for Cosmos SQL Container %q (Account: %q, Database: %q): %+v - "+ "If the collection has not been created with an initial throughput, you cannot configure it later", id.ContainerName, id.DatabaseAccountName, id.SqlDatabaseName, err) - } } diff --git a/internal/services/dashboard/dashboard_grafana_managed_private_endpoint_resource_test.go b/internal/services/dashboard/dashboard_grafana_managed_private_endpoint_resource_test.go index 92f4ae2b4290..23f06f23819a 100644 --- a/internal/services/dashboard/dashboard_grafana_managed_private_endpoint_resource_test.go +++ b/internal/services/dashboard/dashboard_grafana_managed_private_endpoint_resource_test.go @@ -146,7 +146,6 @@ resource "azurerm_dashboard_grafana_managed_private_endpoint" "import" { private_link_resource_id = azurerm_dashboard_grafana_managed_private_endpoint.test.private_link_resource_id } `, config) - } func (r ManagedPrivateEndpointResource) complete(data acceptance.TestData) string { diff --git a/internal/services/dashboard/dashboard_grafana_resource.go b/internal/services/dashboard/dashboard_grafana_resource.go index 7a99dbb6776e..2b0b01bacbcd 100644 --- a/internal/services/dashboard/dashboard_grafana_resource.go +++ b/internal/services/dashboard/dashboard_grafana_resource.go @@ -557,7 +557,7 @@ func expandGrafanaIntegrationsModel(inputList []AzureMonitorWorkspaceIntegration } func expandAzureMonitorWorkspaceIntegrationModelArray(inputList []AzureMonitorWorkspaceIntegrationModel) *[]grafanaresource.AzureMonitorWorkspaceIntegration { - var outputList []grafanaresource.AzureMonitorWorkspaceIntegration + outputList := make([]grafanaresource.AzureMonitorWorkspaceIntegration, 0, len(inputList)) for _, v := range inputList { input := v output := grafanaresource.AzureMonitorWorkspaceIntegration{ @@ -622,17 +622,15 @@ func flattenSMTPConfigurationModel(input *grafanaresource.Smtp, data *schema.Res output.Password = data.Get("smtp.0.password").(string) - outputList = append(outputList, output) - - return outputList + return append(outputList, output) } func flattenAzureMonitorWorkspaceIntegrationModelArray(inputList *[]grafanaresource.AzureMonitorWorkspaceIntegration) []AzureMonitorWorkspaceIntegrationModel { - var outputList []AzureMonitorWorkspaceIntegrationModel if inputList == nil { - return outputList + return []AzureMonitorWorkspaceIntegrationModel{} } + outputList := make([]AzureMonitorWorkspaceIntegrationModel, 0, len(*inputList)) for _, input := range *inputList { output := AzureMonitorWorkspaceIntegrationModel{} diff --git a/internal/services/databoxedge/migration/device_edge_order_v0_to_v1.go b/internal/services/databoxedge/migration/device_edge_order_v0_to_v1.go index 3d57b8aae4ea..9a3df438fb3f 100644 --- a/internal/services/databoxedge/migration/device_edge_order_v0_to_v1.go +++ b/internal/services/databoxedge/migration/device_edge_order_v0_to_v1.go @@ -5,6 +5,7 @@ package migration import ( "context" + "errors" "fmt" "log" @@ -266,11 +267,11 @@ func parseLegacyResourceID(input string) (*legacyResourceId, error) { } if resourceId.SubscriptionId == "" { - return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + return nil, errors.New("ID was missing the 'subscriptions' element") } if resourceId.ResourceGroupName == "" { - return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + return nil, errors.New("ID was missing the 'resourceGroups' element") } if resourceId.DataBoxEdgeDeviceName, err = id.PopSegment("dataBoxEdgeDevices"); err != nil { diff --git a/internal/services/databricks/databricks_customer_managed_key_resource.go b/internal/services/databricks/databricks_customer_managed_key_resource.go index ea086fb7d0dc..51320bfcf2e5 100644 --- a/internal/services/databricks/databricks_customer_managed_key_resource.go +++ b/internal/services/databricks/databricks_customer_managed_key_resource.go @@ -196,7 +196,6 @@ func databricksWorkspaceCustomerManagedKeyRead(d *pluginsdk.ResourceData, meta i if model := resp.Model; model != nil { if model.Properties.Parameters != nil { if props := model.Properties.Parameters.Encryption; props != nil { - if props.Value.KeySource != nil { keySource = string(*props.Value.KeySource) } diff --git a/internal/services/databricks/databricks_workspace_resource.go b/internal/services/databricks/databricks_workspace_resource.go index 8dcc93dcb518..33f1f0af7bdf 100644 --- a/internal/services/databricks/databricks_workspace_resource.go +++ b/internal/services/databricks/databricks_workspace_resource.go @@ -627,7 +627,6 @@ func resourceDatabricksWorkspaceCreateUpdate(d *pluginsdk.ResourceData, meta int } if accessConnector.Model.Identity != nil { - accIdentityId := "" for raw := range accessConnector.Model.Identity.IdentityIds { id, err := commonids.ParseUserAssignedIdentityIDInsensitively(raw) diff --git a/internal/services/datafactory/azuresdkhacks/pipelines.go b/internal/services/datafactory/azuresdkhacks/pipelines.go index b53054d557e9..bb439ed577fd 100644 --- a/internal/services/datafactory/azuresdkhacks/pipelines.go +++ b/internal/services/datafactory/azuresdkhacks/pipelines.go @@ -67,21 +67,18 @@ func (client PipelinesClient) CreateOrUpdate(ctx context.Context, resourceGroupN req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, factoryName, pipelineName, pipeline, ifMatch) if err != nil { - err = autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "CreateOrUpdate", nil, "Failure preparing request") - return + return result, autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.OriginalClient.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "CreateOrUpdate", resp, "Failure sending request") - return + return result, autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "CreateOrUpdate", resp, "Failure responding to request") - return + return result, autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -157,24 +154,21 @@ func (client PipelinesClient) Get(ctx context.Context, resourceGroupName string, req, err := client.GetPreparer(ctx, resourceGroupName, factoryName, pipelineName, ifNoneMatch) if err != nil { - err = autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "Get", nil, "Failure preparing request") - return + return result, autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "Get", nil, "Failure preparing request") } resp, err := client.OriginalClient.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "Get", resp, "Failure sending request") - return + return result, autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "Get", resp, "Failure responding to request") - return + return result, autorest.NewErrorWithError(err, "datafactory.PipelinesClient", "Get", resp, "Failure responding to request") } - return + return result, err } func (client PipelinesClient) GetPreparer(ctx context.Context, resourceGroupName string, factoryName string, pipelineName string, ifNoneMatch string) (*http.Request, error) { diff --git a/internal/services/datafactory/data_factory.go b/internal/services/datafactory/data_factory.go index 939ce512a51c..ba2676cc6fd2 100644 --- a/internal/services/datafactory/data_factory.go +++ b/internal/services/datafactory/data_factory.go @@ -146,9 +146,9 @@ func flattenDataFactoryVariables(input map[string]*datafactory.VariableSpecifica // DatasetColumn describes the attributes needed to specify a structure column for a dataset type DatasetColumn struct { - Name string `json:"name,omitempty" tfschema:"name"` + Name string `json:"name,omitempty" tfschema:"name"` Description string `json:"description,omitempty" tfschema:"description"` - Type string `json:"type,omitempty" tfschema:"type"` + Type string `json:"type,omitempty" tfschema:"type"` } func expandDataFactoryDatasetStructure(input []interface{}) interface{} { diff --git a/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go b/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go index 3e2456cfdb88..d5af5e7357a3 100644 --- a/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go +++ b/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go @@ -234,7 +234,6 @@ func getManagedPrivateEndpoint(ctx context.Context, client *managedprivateendpoi if item.Name != nil && *item.Name == privateEndpointName { return &item, nil } - } return nil, nil } diff --git a/internal/services/datafactory/data_factory_trigger_schedule_data_source.go b/internal/services/datafactory/data_factory_trigger_schedule_data_source.go index 07094cabf6d5..5d6b99161595 100644 --- a/internal/services/datafactory/data_factory_trigger_schedule_data_source.go +++ b/internal/services/datafactory/data_factory_trigger_schedule_data_source.go @@ -256,7 +256,6 @@ func (d TriggerScheduleDataSource) Read() sdk.ResourceFunc { if scheduleTriggerProps.Description != nil { model.Description = *scheduleTriggerProps.Description } - } if err := metadata.Encode(&model); err != nil { return fmt.Errorf("encoding: %+v", err) diff --git a/internal/services/datafactory/data_factory_trigger_tumbling_window_resource.go b/internal/services/datafactory/data_factory_trigger_tumbling_window_resource.go index 63ed0e88c5c8..9c1b6af2533d 100644 --- a/internal/services/datafactory/data_factory_trigger_tumbling_window_resource.go +++ b/internal/services/datafactory/data_factory_trigger_tumbling_window_resource.go @@ -439,7 +439,7 @@ func expandDataFactoryTriggerDependency(input []interface{}) *[]datafactory.Basi return nil } - var result []datafactory.BasicDependencyReference + result := make([]datafactory.BasicDependencyReference, 0, len(input)) for _, item := range input { raw := item.(map[string]interface{}) diff --git a/internal/services/datashare/data_share_dataset_blob_storage_data_source.go b/internal/services/datashare/data_share_dataset_blob_storage_data_source.go index 2afead4424cc..6d638130940a 100644 --- a/internal/services/datashare/data_share_dataset_blob_storage_data_source.go +++ b/internal/services/datashare/data_share_dataset_blob_storage_data_source.go @@ -111,7 +111,6 @@ func dataSourceDataShareDatasetBlobStorageRead(d *pluginsdk.ResourceData, meta i } d.Set("file_path", props.FilePath) d.Set("display_name", props.DataSetId) - } else if ds, ok := model.(dataset.BlobFolderDataSet); ok { props := ds.Properties d.Set("container_name", props.ContainerName) diff --git a/internal/services/datashare/data_share_dataset_blob_storage_resource.go b/internal/services/datashare/data_share_dataset_blob_storage_resource.go index 1733e001c317..6f627e13f5f9 100644 --- a/internal/services/datashare/data_share_dataset_blob_storage_resource.go +++ b/internal/services/datashare/data_share_dataset_blob_storage_resource.go @@ -206,7 +206,6 @@ func resourceDataShareDataSetBlobStorageRead(d *pluginsdk.ResourceData, meta int } d.Set("file_path", props.FilePath) d.Set("display_name", props.DataSetId) - } else if ds, ok := model.(dataset.BlobFolderDataSet); ok { props := ds.Properties d.Set("container_name", props.ContainerName) diff --git a/internal/services/devcenter/client/client_gen.go b/internal/services/devcenter/client/client_gen.go index 854a50a45e06..1a682d975805 100644 --- a/internal/services/devcenter/client/client_gen.go +++ b/internal/services/devcenter/client/client_gen.go @@ -13,7 +13,6 @@ type AutoClient struct { } func NewClient(o *common.ClientOptions) (*AutoClient, error) { - v20230401Client, err := devcenterV20230401.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { o.Configure(c, o.Authorizers.ResourceManager) }) diff --git a/internal/services/devcenter/dev_center_resource_gen.go b/internal/services/devcenter/dev_center_resource_gen.go index e0dd108e63d1..752add149b7a 100644 --- a/internal/services/devcenter/dev_center_resource_gen.go +++ b/internal/services/devcenter/dev_center_resource_gen.go @@ -193,7 +193,6 @@ func (r DevCenterResource) Update() sdk.ResourceFunc { } func (r DevCenterResource) mapDevCenterResourceSchemaToDevCenter(input DevCenterResourceSchema, output *devcenters.DevCenter) error { - identity, err := identity.ExpandSystemAndUserAssignedMapFromModel(input.Identity) if err != nil { return fmt.Errorf("expanding SystemAndUserAssigned Identity: %+v", err) @@ -214,7 +213,6 @@ func (r DevCenterResource) mapDevCenterResourceSchemaToDevCenter(input DevCenter } func (r DevCenterResource) mapDevCenterToDevCenterResourceSchema(input devcenters.DevCenter, output *DevCenterResourceSchema) error { - identity, err := identity.FlattenSystemAndUserAssignedMapToModel(input.Identity) if err != nil { return fmt.Errorf("flattening SystemAndUserAssigned Identity: %+v", err) @@ -235,7 +233,6 @@ func (r DevCenterResource) mapDevCenterToDevCenterResourceSchema(input devcenter } func (r DevCenterResource) mapDevCenterResourceSchemaToDevCenterProperties(input DevCenterResourceSchema, output *devcenters.DevCenterProperties) error { - return nil } diff --git a/internal/services/devtestlabs/dev_test_lab_data_source.go b/internal/services/devtestlabs/dev_test_lab_data_source.go index a8de56d86a14..bb480ce953ce 100644 --- a/internal/services/devtestlabs/dev_test_lab_data_source.go +++ b/internal/services/devtestlabs/dev_test_lab_data_source.go @@ -101,7 +101,6 @@ func dataSourceDevTestLabRead(d *pluginsdk.ResourceData, meta interface{}) error d.Set("resource_group_name", id.ResourceGroupName) if model := resp.Model; model != nil { - d.Set("location", location.NormalizeNilable(model.Location)) if props := model.Properties; props != nil { diff --git a/internal/services/dynatrace/dynatrace_monitors_resource.go b/internal/services/dynatrace/dynatrace_monitors_resource.go index c5f2c7b6f012..13cd7d7d191a 100644 --- a/internal/services/dynatrace/dynatrace_monitors_resource.go +++ b/internal/services/dynatrace/dynatrace_monitors_resource.go @@ -2,6 +2,7 @@ package dynatrace import ( "context" + "errors" "fmt" "time" @@ -362,7 +363,7 @@ func expandDynatraceIdentity(input []identity.ModelSystemAssigned) (*monitors.Id func flattenDynatraceIdentity(input *monitors.IdentityProperties) ([]identity.ModelSystemAssigned, error) { if input == nil { - return nil, fmt.Errorf("flattening Dynatrace identity: input is nil") + return nil, errors.New("flattening Dynatrace identity: input is nil") } var identityProp identity.ModelSystemAssigned diff --git a/internal/services/elasticsan/elastic_san_volume_group_resource.go b/internal/services/elasticsan/elastic_san_volume_group_resource.go index 34d2e2a62083..b6ece6102215 100644 --- a/internal/services/elasticsan/elastic_san_volume_group_resource.go +++ b/internal/services/elasticsan/elastic_san_volume_group_resource.go @@ -440,7 +440,7 @@ func ExpandVolumeGroupNetworkRules(input []ElasticSANVolumeGroupResourceNetworkR } } - var networkRules []volumegroups.VirtualNetworkRule + networkRules := make([]volumegroups.VirtualNetworkRule, 0, len(input)) for _, rule := range input { networkRules = append(networkRules, volumegroups.VirtualNetworkRule{ Id: rule.SubnetId, diff --git a/internal/services/eventhub/eventhub_resource.go b/internal/services/eventhub/eventhub_resource.go index b3cb1e5f8465..71b2d21b6ab5 100644 --- a/internal/services/eventhub/eventhub_resource.go +++ b/internal/services/eventhub/eventhub_resource.go @@ -221,7 +221,6 @@ func resourceEventHubUpdate(d *pluginsdk.ResourceData, meta interface{}) error { id := eventhubs.NewEventhubID(subscriptionId, d.Get("resource_group_name").(string), d.Get("namespace_name").(string), d.Get("name").(string)) if d.HasChange("partition_count") { - o, n := d.GetChange("partition_count") if o.(int) > n.(int) { return fmt.Errorf("`partition_count` cannot be decreased") diff --git a/internal/services/eventhub/validate/eventhub_message_retention.go b/internal/services/eventhub/validate/eventhub_message_retention.go index 3945dcc7cb73..23a22493ec3e 100644 --- a/internal/services/eventhub/validate/eventhub_message_retention.go +++ b/internal/services/eventhub/validate/eventhub_message_retention.go @@ -3,14 +3,14 @@ package validate -import "fmt" +import "errors" -func ValidateEventHubMessageRetentionCount(v interface{}, _ string) (warnings []string, errors []error) { +func ValidateEventHubMessageRetentionCount(v interface{}, _ string) (warnings []string, errs []error) { value := v.(int) if !(90 >= value && value >= 1) { - errors = append(errors, fmt.Errorf("EventHub Retention Count has to be between 1 and 7 or between 1 and 90 if using a dedicated Event Hubs Cluster")) + errs = append(errs, errors.New("EventHub Retention Count has to be between 1 and 7 or between 1 and 90 if using a dedicated Event Hubs Cluster")) } - return warnings, errors + return warnings, errs } diff --git a/internal/services/eventhub/validate/eventhub_partition.go b/internal/services/eventhub/validate/eventhub_partition.go index d6768d191e84..50f129470bcd 100644 --- a/internal/services/eventhub/validate/eventhub_partition.go +++ b/internal/services/eventhub/validate/eventhub_partition.go @@ -3,14 +3,14 @@ package validate -import "fmt" +import "errors" -func ValidateEventHubPartitionCount(v interface{}, _ string) (warnings []string, errors []error) { +func ValidateEventHubPartitionCount(v interface{}, _ string) (warnings []string, errs []error) { value := v.(int) if !(1024 >= value && value >= 1) { - errors = append(errors, fmt.Errorf("EventHub Partition Count has to be between 1 and 32 or between 1 and 1024 if using a dedicated Event Hubs Cluster")) + errs = append(errs, errors.New("EventHub Partition Count has to be between 1 and 32 or between 1 and 1024 if using a dedicated Event Hubs Cluster")) } - return warnings, errors + return warnings, errs } diff --git a/internal/services/firewall/firewall_application_rule_collection_resource.go b/internal/services/firewall/firewall_application_rule_collection_resource.go index 258a7673d7f1..03e7228d40b1 100644 --- a/internal/services/firewall/firewall_application_rule_collection_resource.go +++ b/internal/services/firewall/firewall_application_rule_collection_resource.go @@ -230,7 +230,6 @@ func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.Resource if read.Model == nil { return fmt.Errorf("retrieving %s: `model` was nil", firewallId) - } var collectionID string diff --git a/internal/services/firewall/firewall_nat_rule_collection_resource.go b/internal/services/firewall/firewall_nat_rule_collection_resource.go index 3c649e2d9a95..bd4bea91ebf9 100644 --- a/internal/services/firewall/firewall_nat_rule_collection_resource.go +++ b/internal/services/firewall/firewall_nat_rule_collection_resource.go @@ -228,7 +228,6 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me if read.Model == nil { return fmt.Errorf("retrieving %s: `model` was nil", firewallId) - } var collectionID string diff --git a/internal/services/firewall/firewall_network_rule_collection_resource.go b/internal/services/firewall/firewall_network_rule_collection_resource.go index 3780e1c7cbb8..c665f733e039 100644 --- a/internal/services/firewall/firewall_network_rule_collection_resource.go +++ b/internal/services/firewall/firewall_network_rule_collection_resource.go @@ -231,7 +231,6 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData if read.Model == nil { return fmt.Errorf("retrieving %s: `model` was nil", firewallId) - } var collectionID string diff --git a/internal/services/firewall/firewall_policy_resource.go b/internal/services/firewall/firewall_policy_resource.go index 4ae96dbfb789..9aecb88236ae 100644 --- a/internal/services/firewall/firewall_policy_resource.go +++ b/internal/services/firewall/firewall_policy_resource.go @@ -295,7 +295,7 @@ func expandFirewallPolicyDNSSetting(input []interface{}) *firewallpolicies.DnsSe raw := input[0].(map[string]interface{}) output := &firewallpolicies.DnsSettings{ Servers: utils.ExpandStringSlice(raw["servers"].([]interface{})), - EnableProxy: utils.Bool(raw["proxy_enabled"].(bool)), + EnableProxy: pointer.To(raw["proxy_enabled"].(bool)), } return output @@ -308,22 +308,23 @@ func expandFirewallPolicyIntrusionDetection(input []interface{}) *firewallpolici raw := input[0].(map[string]interface{}) - var signatureOverrides []firewallpolicies.FirewallPolicyIntrusionDetectionSignatureSpecification - for _, v := range raw["signature_overrides"].([]interface{}) { + signatureOverridesRaw := raw["signature_overrides"].([]interface{}) + signatureOverrides := make([]firewallpolicies.FirewallPolicyIntrusionDetectionSignatureSpecification, 0, len(signatureOverridesRaw)) + for _, v := range signatureOverridesRaw { overrides := v.(map[string]interface{}) signatureOverrides = append(signatureOverrides, firewallpolicies.FirewallPolicyIntrusionDetectionSignatureSpecification{ - Id: utils.String(overrides["id"].(string)), + Id: pointer.To(overrides["id"].(string)), Mode: pointer.To(firewallpolicies.FirewallPolicyIntrusionDetectionStateType(overrides["state"].(string))), }) } - var trafficBypass []firewallpolicies.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications - - for _, v := range raw["traffic_bypass"].([]interface{}) { + trafficBypassRaw := raw["traffic_bypass"].([]interface{}) + trafficBypass := make([]firewallpolicies.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications, 0, len(trafficBypassRaw)) + for _, v := range trafficBypassRaw { bypass := v.(map[string]interface{}) trafficBypass = append(trafficBypass, firewallpolicies.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications{ - Name: utils.String(bypass["name"].(string)), - Description: utils.String(bypass["description"].(string)), + Name: pointer.To(bypass["name"].(string)), + Description: pointer.To(bypass["description"].(string)), Protocol: pointer.To(firewallpolicies.FirewallPolicyIntrusionDetectionProtocol(bypass["protocol"].(string))), SourceAddresses: utils.ExpandStringSlice(bypass["source_addresses"].(*pluginsdk.Set).List()), DestinationAddresses: utils.ExpandStringSlice(bypass["destination_addresses"].(*pluginsdk.Set).List()), @@ -333,8 +334,9 @@ func expandFirewallPolicyIntrusionDetection(input []interface{}) *firewallpolici }) } - var privateRanges []string - for _, v := range raw["private_ranges"].([]interface{}) { + privateRangesRaw := raw["private_ranges"].([]interface{}) + privateRanges := make([]string, 0, len(privateRangesRaw)) + for _, v := range privateRangesRaw { privateRanges = append(privateRanges, v.(string)) } @@ -410,7 +412,7 @@ func expandFirewallPolicyLogAnalyticsResources(defaultWorkspaceId string, worksp }, } - var workspaceList []firewallpolicies.FirewallPolicyLogAnalyticsWorkspace + workspaceList := make([]firewallpolicies.FirewallPolicyLogAnalyticsWorkspace, 0, len(workspaces)) for _, workspace := range workspaces { workspace := workspace.(map[string]interface{}) workspaceList = append(workspaceList, firewallpolicies.FirewallPolicyLogAnalyticsWorkspace{ diff --git a/internal/services/fluidrelay/validate/server_name.go b/internal/services/fluidrelay/validate/server_name.go index 047c441ea6dc..d33529384137 100644 --- a/internal/services/fluidrelay/validate/server_name.go +++ b/internal/services/fluidrelay/validate/server_name.go @@ -4,21 +4,22 @@ package validate import ( + "errors" "fmt" "regexp" ) var serverNameReg = regexp.MustCompile(`^[-0-9a-zA-Z]{1,50}$`) -func FluidRelayServerName(input interface{}, key string) (warnings []string, errors []error) { +func FluidRelayServerName(input interface{}, key string) (warnings []string, errs []error) { v, ok := input.(string) if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + errs = append(errs, fmt.Errorf("expected %q to be a string", key)) return } // Name should contain only alphanumeric characters and hyphens, up to 50 characters long. if !serverNameReg.MatchString(v) { - errors = append(errors, fmt.Errorf("Name should contain only alphanumeric characters and hyphens, up to 50 characters long.")) + errs = append(errs, errors.New("Name should contain only alphanumeric characters and hyphens, up to 50 characters long.")) } return } diff --git a/internal/services/frontdoor/customizediff.go b/internal/services/frontdoor/customizediff.go index 5cfb9bfcdfde..e42295ec9172 100644 --- a/internal/services/frontdoor/customizediff.go +++ b/internal/services/frontdoor/customizediff.go @@ -5,6 +5,7 @@ package frontdoor import ( "context" + "errors" "fmt" "strings" @@ -34,7 +35,7 @@ func customHttpsSettings(d *pluginsdk.ResourceDiff) error { if len(frontendEndpointCustomHttpsConfig) > 0 { if !customHttpsEnabled { - return fmt.Errorf(`"custom_https_provisioning_enabled" is set to "false". please remove the "custom_https_configuration" block from the configuration file`) + return errors.New(`"custom_https_provisioning_enabled" is set to "false". please remove the "custom_https_configuration" block from the configuration file`) } // Verify frontend endpoints custom https configuration is valid if defined @@ -42,7 +43,7 @@ func customHttpsSettings(d *pluginsdk.ResourceDiff) error { return err } } else if customHttpsEnabled { - return fmt.Errorf(`"custom_https_provisioning_enabled" is set to "true". please add a "custom_https_configuration" block to the configuration file`) + return errors.New(`"custom_https_provisioning_enabled" is set to "true". please add a "custom_https_configuration" block to the configuration file`) } return nil @@ -56,21 +57,21 @@ func verifyCustomHttpsConfiguration(frontendEndpointCustomHttpsConfig []interfac if certificateSource == string(frontdoors.FrontDoorCertificateSourceFrontDoor) { if azureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { - return fmt.Errorf(`a Front Door managed "custom_https_configuration" block does not support the following keys. Please remove the following keys from your configuration file: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`) + return errors.New(`a Front Door managed "custom_https_configuration" block does not support the following keys. Please remove the following keys from your configuration file: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`) } } else { // The latest secret version is no longer valid for key vaults if strings.EqualFold(certificateVersion, "latest") { - return fmt.Errorf(`"azure_key_vault_certificate_secret_version" can not be set to "latest" please remove this attribute from the configuration file. Removing the value has the same functionality as setting it to "latest"`) + return errors.New(`"azure_key_vault_certificate_secret_version" can not be set to "latest" please remove this attribute from the configuration file. Removing the value has the same functionality as setting it to "latest"`) } if !azureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { if certificateVersion == "" { // If using latest, empty string is now equivalent to using the keyword latest - return fmt.Errorf(`a "AzureKeyVault" managed "custom_https_configuration" block must have values in the following fileds: "azure_key_vault_certificate_secret_name" and "azure_key_vault_certificate_vault_id"`) + return errors.New(`a "AzureKeyVault" managed "custom_https_configuration" block must have values in the following fileds: "azure_key_vault_certificate_secret_name" and "azure_key_vault_certificate_vault_id"`) } else { // If using a specific version of the secret - return fmt.Errorf(`a "AzureKeyVault" managed "custom_https_configuration" block must have values in the following fileds: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`) + return errors.New(`a "AzureKeyVault" managed "custom_https_configuration" block must have values in the following fileds: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`) } } } @@ -122,7 +123,7 @@ func frontDoorSettings(d *pluginsdk.ResourceDiff) error { healthProbeSettings := d.Get("backend_pool_health_probe").([]interface{}) if len(configFrontendEndpoints) == 0 { - return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) + return errors.New(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) } // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule diff --git a/internal/services/graphservices/client/client.go b/internal/services/graphservices/client/client.go index fe9bae33c853..be3ebd1fc97c 100644 --- a/internal/services/graphservices/client/client.go +++ b/internal/services/graphservices/client/client.go @@ -16,7 +16,6 @@ type Client struct { } func NewClient(o *common.ClientOptions) (*Client, error) { - v20230413Client, err := graphservicesV20230413.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { o.Configure(c, o.Authorizers.ResourceManager) }) diff --git a/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go b/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go index ce45c20b03a0..6e6d92ba9cca 100644 --- a/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go +++ b/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go @@ -415,7 +415,6 @@ func resourceHDInsightKafkaClusterRead(d *pluginsdk.ResourceData, meta interface d.Set("resource_group_name", id.ResourceGroupName) if model := resp.Model; model != nil { - d.Set("location", location.Normalize(model.Location)) // storage_account isn't returned so I guess we just leave it ¯\_(ツ)_/¯ diff --git a/internal/services/healthcare/healthcare_dicom_data_source.go b/internal/services/healthcare/healthcare_dicom_data_source.go index c2233ddcb1eb..f778c84641fd 100644 --- a/internal/services/healthcare/healthcare_dicom_data_source.go +++ b/internal/services/healthcare/healthcare_dicom_data_source.go @@ -134,7 +134,6 @@ func dataSourceHealthcareApisDicomServiceRead(d *pluginsdk.ResourceData, meta in } return tags.FlattenAndSet(d, m.Tags) - } return nil } diff --git a/internal/services/healthcare/healthcare_fhir_resource.go b/internal/services/healthcare/healthcare_fhir_resource.go index 2420b87b5e64..6ec7a020c781 100644 --- a/internal/services/healthcare/healthcare_fhir_resource.go +++ b/internal/services/healthcare/healthcare_fhir_resource.go @@ -600,9 +600,7 @@ func flattenFhirAccessPolicy(policies *[]fhirservices.FhirServiceAccessPolicyEnt } for _, policy := range *policies { - result = append(result, policy.ObjectId) - } return result } diff --git a/internal/services/healthcare/healthcare_medtech_service_fhir_destination_resource.go b/internal/services/healthcare/healthcare_medtech_service_fhir_destination_resource.go index d0f4a295d9a4..4fd2f21d56d8 100644 --- a/internal/services/healthcare/healthcare_medtech_service_fhir_destination_resource.go +++ b/internal/services/healthcare/healthcare_medtech_service_fhir_destination_resource.go @@ -245,7 +245,6 @@ func resourceHealthcareApisMedTechServiceFhirDestinationDelete(d *pluginsdk.Reso err = client.IotConnectorFhirDestinationDeleteThenPoll(ctx, *id) if err != nil { - return fmt.Errorf("deleting %s: %+v", *id, err) } log.Printf("[DEBUG] Waiting for %s to be deleted..", id) diff --git a/internal/services/healthcare/healthcare_service_resource.go b/internal/services/healthcare/healthcare_service_resource.go index 952406e0aa45..cd35d102723a 100644 --- a/internal/services/healthcare/healthcare_service_resource.go +++ b/internal/services/healthcare/healthcare_service_resource.go @@ -462,7 +462,6 @@ func flattenAccessPolicies(policies *[]service.ServiceAccessPolicyEntry) []strin for _, policy := range *policies { result = append(result, policy.ObjectId) - } return result diff --git a/internal/services/hybridcompute/arc_machine_data_source.go b/internal/services/hybridcompute/arc_machine_data_source.go index dcad6911d735..4658e5cb0b70 100644 --- a/internal/services/hybridcompute/arc_machine_data_source.go +++ b/internal/services/hybridcompute/arc_machine_data_source.go @@ -681,11 +681,11 @@ func flattenAgentConfigurationModel(input *machines.AgentConfiguration) ([]Agent } func flattenConfigurationExtensionModel(inputList *[]machines.ConfigurationExtension) []ConfigurationExtensionModel { - var outputList []ConfigurationExtensionModel if inputList == nil { - return outputList + return []ConfigurationExtensionModel{} } + outputList := make([]ConfigurationExtensionModel, 0, len(*inputList)) for _, input := range *inputList { output := ConfigurationExtensionModel{} diff --git a/internal/services/hybridcompute/arc_machine_extension_resource.go b/internal/services/hybridcompute/arc_machine_extension_resource.go index eef8d900c58c..6950202573d6 100644 --- a/internal/services/hybridcompute/arc_machine_extension_resource.go +++ b/internal/services/hybridcompute/arc_machine_extension_resource.go @@ -366,7 +366,6 @@ func (r ArcMachineExtensionResource) Read() sdk.ResourceFunc { } if properties.Settings != nil && *properties.Settings != nil { - settingsValue, err := json.Marshal(*properties.Settings) if err != nil { return err @@ -387,7 +386,6 @@ func (r ArcMachineExtensionResource) Read() sdk.ResourceFunc { if model.Tags != nil { state.Tags = *model.Tags } - } return metadata.Encode(&state) diff --git a/internal/services/iotcentral/client/client.go b/internal/services/iotcentral/client/client.go index c424db661255..3347b9e6660b 100644 --- a/internal/services/iotcentral/client/client.go +++ b/internal/services/iotcentral/client/client.go @@ -5,6 +5,7 @@ package client import ( "context" + "errors" "fmt" "github.com/Azure/go-autorest/autorest" @@ -40,7 +41,7 @@ func NewClient(o *common.ClientOptions) (*Client, error) { func (c *Client) OrganizationsClient(ctx context.Context, subdomain string) (*dataplane.OrganizationsClient, error) { if !c.Endpoint.Available() { - return nil, fmt.Errorf("unable to build SDK Client since IoTCentral is not available in this Azure Environment") + return nil, errors.New("unable to build SDK Client since IoTCentral is not available in this Azure Environment") } iotCentralAuth, err := c.authorizerFunc(c.Endpoint) diff --git a/internal/services/kusto/kusto_cluster_resource.go b/internal/services/kusto/kusto_cluster_resource.go index b373a13395d3..e58360f6cba8 100644 --- a/internal/services/kusto/kusto_cluster_resource.go +++ b/internal/services/kusto/kusto_cluster_resource.go @@ -635,7 +635,6 @@ func resourceKustoClusterRead(d *pluginsdk.ResourceData, meta interface{}) error } else { d.Set("language_extensions", flattenKustoClusterLanguageExtensions(props.LanguageExtensions)) } - } if err := tags.FlattenAndSet(d, model.Tags); err != nil { diff --git a/internal/services/legacy/virtual_machine_scale_set_resource_test.go b/internal/services/legacy/virtual_machine_scale_set_resource_test.go index d78cd967e0f9..77906bdd1210 100644 --- a/internal/services/legacy/virtual_machine_scale_set_resource_test.go +++ b/internal/services/legacy/virtual_machine_scale_set_resource_test.go @@ -830,7 +830,6 @@ func (VirtualMachineScaleSetResource) hasLoadBalancer(ctx context.Context, clien } } } - } return fmt.Errorf("load balancer configuration was missing") diff --git a/internal/services/lighthouse/lighthouse_definition_resource.go b/internal/services/lighthouse/lighthouse_definition_resource.go index 9dd3e1dedb24..f27ac2963e7d 100644 --- a/internal/services/lighthouse/lighthouse_definition_resource.go +++ b/internal/services/lighthouse/lighthouse_definition_resource.go @@ -400,8 +400,7 @@ func expandLighthouseDefinitionEligibleAuthorization(input []interface{}) *[]reg return nil } - var results []registrationdefinitions.EligibleAuthorization - + results := make([]registrationdefinitions.EligibleAuthorization, 0, len(input)) for _, item := range input { v := item.(map[string]interface{}) @@ -447,8 +446,7 @@ func expandLighthouseDefinitionApprover(input []interface{}) *[]registrationdefi return nil } - var results []registrationdefinitions.EligibleApprover - + results := make([]registrationdefinitions.EligibleApprover, 0) for _, v := range input { eligibleApprover := v.(map[string]interface{}) @@ -471,8 +469,7 @@ func flattenLighthouseDefinitionEligibleAuthorization(input *[]registrationdefin return nil } - var results []interface{} - + results := make([]interface{}, 0, len(*input)) for _, item := range *input { result := map[string]interface{}{ "principal_id": item.PrincipalId, @@ -524,8 +521,7 @@ func flattenLighthouseDefinitionApprover(input *[]registrationdefinitions.Eligib return nil } - var results []interface{} - + results := make([]interface{}, 0, len(*input)) for _, item := range *input { result := map[string]interface{}{ "principal_id": item.PrincipalId, diff --git a/internal/services/loadbalancer/backend_address_pool_data_source.go b/internal/services/loadbalancer/backend_address_pool_data_source.go index 1b98c43acb4a..abea1ba59ab0 100644 --- a/internal/services/loadbalancer/backend_address_pool_data_source.go +++ b/internal/services/loadbalancer/backend_address_pool_data_source.go @@ -225,7 +225,6 @@ func flattenArmLoadBalancerBackendAddresses(input *[]loadbalancers.LoadBalancerB ) var inboundNATRulePortMappingList []interface{} if prop := e.Properties; prop != nil { - ipAddress = pointer.From(prop.IPAddress) if prop.VirtualNetwork != nil { diff --git a/internal/services/loadbalancer/loadbalancer_data_source.go b/internal/services/loadbalancer/loadbalancer_data_source.go index 5373b817aa59..3d89b4b48073 100644 --- a/internal/services/loadbalancer/loadbalancer_data_source.go +++ b/internal/services/loadbalancer/loadbalancer_data_source.go @@ -163,7 +163,6 @@ func dataSourceArmLoadBalancerRead(d *pluginsdk.ResourceData, meta interface{}) } return nil - } func flattenLoadBalancerDataSourceFrontendIpConfiguration(ipConfigs *[]loadbalancers.FrontendIPConfiguration) []interface{} { diff --git a/internal/services/loadtestservice/client/client.go b/internal/services/loadtestservice/client/client.go index 7e29654ffe82..4d6772539544 100644 --- a/internal/services/loadtestservice/client/client.go +++ b/internal/services/loadtestservice/client/client.go @@ -16,7 +16,6 @@ type AutoClient struct { } func NewClient(o *common.ClientOptions) (*AutoClient, error) { - v20221201Client, err := loadtestserviceV20221201.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { o.Configure(c, o.Authorizers.ResourceManager) }) diff --git a/internal/services/loadtestservice/load_test_resource.go b/internal/services/loadtestservice/load_test_resource.go index f344fb45cd30..227b6b6b2371 100644 --- a/internal/services/loadtestservice/load_test_resource.go +++ b/internal/services/loadtestservice/load_test_resource.go @@ -296,7 +296,6 @@ func (r LoadTestResource) mapLoadTestPropertiesToLoadTestResourceSchema(input lo } func (r LoadTestResource) mapLoadTestResourceSchemaToLoadTestResource(input LoadTestResourceSchema, output *loadtests.LoadTestResource) error { - identity, err := identity.ExpandLegacySystemAndUserAssignedMapFromModel(input.Identity) if err != nil { return fmt.Errorf("expanding Legacy SystemAndUserAssigned Identity: %+v", err) @@ -317,7 +316,6 @@ func (r LoadTestResource) mapLoadTestResourceSchemaToLoadTestResource(input Load } func (r LoadTestResource) mapLoadTestResourceToLoadTestResourceSchema(input loadtests.LoadTestResource, output *LoadTestResourceSchema) error { - identity, err := identity.FlattenLegacySystemAndUserAssignedMapToModel(input.Identity) if err != nil { return fmt.Errorf("flattening Legacy SystemAndUserAssigned Identity: %+v", err) @@ -338,7 +336,6 @@ func (r LoadTestResource) mapLoadTestResourceToLoadTestResourceSchema(input load } func (r LoadTestResource) mapLoadTestResourceSchemaToLoadTestResourceUpdate(input LoadTestResourceSchema, output *loadtests.LoadTestResourceUpdate) error { - identity, err := identity.ExpandLegacySystemAndUserAssignedMapFromModel(input.Identity) if err != nil { return fmt.Errorf("expanding Legacy SystemAndUserAssigned Identity: %+v", err) @@ -355,7 +352,6 @@ func (r LoadTestResource) mapLoadTestResourceSchemaToLoadTestResourceUpdate(inpu // nolint: unused func (r LoadTestResource) mapLoadTestResourceUpdateToLoadTestResourceSchema(input loadtests.LoadTestResourceUpdate, output *LoadTestResourceSchema) error { - identity, err := identity.FlattenLegacySystemAndUserAssignedMapToModel(input.Identity) if err != nil { return fmt.Errorf("flattening Legacy SystemAndUserAssigned Identity: %+v", err) diff --git a/internal/services/loganalytics/log_analytics_data_export_resource.go b/internal/services/loganalytics/log_analytics_data_export_resource.go index d7438bd9a299..8f801058aa74 100644 --- a/internal/services/loganalytics/log_analytics_data_export_resource.go +++ b/internal/services/loganalytics/log_analytics_data_export_resource.go @@ -9,6 +9,7 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-11-01/eventhubs" @@ -23,7 +24,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func resourceLogAnalyticsDataExport() *pluginsdk.Resource { @@ -124,8 +124,10 @@ func resourceOperationalinsightsDataExportCreateUpdate(d *pluginsdk.ResourceData } destinationId := d.Get("destination_resource_id").(string) - var tableNames []string - for _, v := range d.Get("table_names").(*pluginsdk.Set).List() { + + tableNamesGet := d.Get("table_names").(*pluginsdk.Set).List() + tableNames := make([]string, 0, len(tableNamesGet)) + for _, v := range tableNamesGet { tableNames = append(tableNames, v.(string)) } @@ -135,27 +137,28 @@ func resourceOperationalinsightsDataExportCreateUpdate(d *pluginsdk.ResourceData ResourceId: destinationId, }, TableNames: tableNames, - Enable: utils.Bool(d.Get("enabled").(bool)), + Enable: pointer.To(d.Get("enabled").(bool)), }, } if strings.Contains(destinationId, "Microsoft.EventHub") { - _, err := eventhubs.ValidateNamespaceID(destinationId, "destination_resource_id") - if err == nil { + if _, err := eventhubs.ValidateNamespaceID(destinationId, "destination_resource_id"); err == nil { eventhubNamespace, err := eventhubs.ParseNamespaceID(destinationId) if err != nil { return fmt.Errorf("parsing destination eventhub namespaces id error: %+v", err) } + parameters.Properties.Destination.ResourceId = eventhubNamespace.ID() } else { eventhubId, err := eventhubs.ParseEventhubID(destinationId) if err != nil { return fmt.Errorf("parsing destination eventhub id error: %+v", err) } + destinationId = namespaces.NewNamespaceID(eventhubId.SubscriptionId, eventhubId.ResourceGroupName, eventhubId.NamespaceName).ID() parameters.Properties.Destination.ResourceId = destinationId parameters.Properties.Destination.MetaData = &dataexport.DestinationMetaData{ - EventHubName: utils.String(eventhubId.EventhubName), + EventHubName: pointer.To(eventhubId.EventhubName), } } } diff --git a/internal/services/loganalytics/log_analytics_solution_resource.go b/internal/services/loganalytics/log_analytics_solution_resource.go index cd395f520ecc..6226fea54e3d 100644 --- a/internal/services/loganalytics/log_analytics_solution_resource.go +++ b/internal/services/loganalytics/log_analytics_solution_resource.go @@ -252,7 +252,6 @@ func (s LogAnalyticsSolutionResource) Read() sdk.ResourceFunc { } state.Tags = pointer.From(model.Tags) - } return metadata.Encode(&state) diff --git a/internal/services/logic/integration_service_environment.go b/internal/services/logic/integration_service_environment.go index 1ad39df184a4..9b00e47bec57 100644 --- a/internal/services/logic/integration_service_environment.go +++ b/internal/services/logic/integration_service_environment.go @@ -503,7 +503,7 @@ func flattenServiceEnvironmentIPAddresses(input *[]integrationserviceenvironment return []interface{}{} } - var addresses []interface{} + addresses := make([]interface{}, 0, len(*input)) for _, addr := range *input { addresses = append(addresses, *addr.Address) } diff --git a/internal/services/logic/logic_app_integration_account_agreement_resource.go b/internal/services/logic/logic_app_integration_account_agreement_resource.go index 68ce92a946f8..9ee6ac6e1e8b 100644 --- a/internal/services/logic/logic_app_integration_account_agreement_resource.go +++ b/internal/services/logic/logic_app_integration_account_agreement_resource.go @@ -236,7 +236,6 @@ func resourceLogicAppIntegrationAccountAgreementRead(d *pluginsdk.ResourceData, if props.Metadata != nil { d.Set("metadata", props.Metadata) } - } return nil diff --git a/internal/services/logic/logic_app_integration_account_assembly_resource.go b/internal/services/logic/logic_app_integration_account_assembly_resource.go index 66e42b2e7dc1..3a626a269c58 100644 --- a/internal/services/logic/logic_app_integration_account_assembly_resource.go +++ b/internal/services/logic/logic_app_integration_account_assembly_resource.go @@ -179,7 +179,6 @@ func resourceLogicAppIntegrationAccountAssemblyRead(d *pluginsdk.ResourceData, m if props.Metadata != nil { d.Set("metadata", props.Metadata) } - } return nil diff --git a/internal/services/logic/logic_app_integration_account_certificate_resource.go b/internal/services/logic/logic_app_integration_account_certificate_resource.go index 42b2d4644dfd..f30e92a342f5 100644 --- a/internal/services/logic/logic_app_integration_account_certificate_resource.go +++ b/internal/services/logic/logic_app_integration_account_certificate_resource.go @@ -178,7 +178,6 @@ func resourceLogicAppIntegrationAccountCertificateRead(d *pluginsdk.ResourceData } d.Set("public_certificate", props.PublicCertificate) - } return nil diff --git a/internal/services/logic/logic_app_workflow_resource.go b/internal/services/logic/logic_app_workflow_resource.go index 3d1d55f31adc..44848ce3f67b 100644 --- a/internal/services/logic/logic_app_workflow_resource.go +++ b/internal/services/logic/logic_app_workflow_resource.go @@ -931,7 +931,7 @@ func flattenIPAddresses(input *[]workflows.IPAddress) []interface{} { return []interface{}{} } - var addresses []interface{} + addresses := make([]interface{}, 0, len(*input)) for _, addr := range *input { addresses = append(addresses, *addr.Address) } diff --git a/internal/services/maintenance/maintenance_assignment_dedicated_host_resource.go b/internal/services/maintenance/maintenance_assignment_dedicated_host_resource.go index 85e64b9ba612..b1ad6dd015a6 100644 --- a/internal/services/maintenance/maintenance_assignment_dedicated_host_resource.go +++ b/internal/services/maintenance/maintenance_assignment_dedicated_host_resource.go @@ -4,6 +4,7 @@ package maintenance import ( + "errors" "fmt" "strings" "time" @@ -114,7 +115,7 @@ func resourceArmMaintenanceAssignmentDedicatedHostCreate(d *pluginsdk.ResourceDa err = pluginsdk.Retry(d.Timeout(pluginsdk.TimeoutCreate), func() *pluginsdk.RetryError { if _, err := client.CreateOrUpdateParent(ctx, id, configurationAssignment); err != nil { if strings.Contains(err.Error(), "It may take a few minutes after starting a VM for it to become available to assign to a configuration") { - return pluginsdk.RetryableError(fmt.Errorf("expected VM is available to assign to a configuration but was in pending state, retrying")) + return pluginsdk.RetryableError(errors.New("expected VM is available to assign to a configuration but was in pending state, retrying")) } return pluginsdk.NonRetryableError(fmt.Errorf("issuing creating request for %s: %+v", id, err)) } diff --git a/internal/services/maintenance/maintenance_assignment_dynamic_scope_resource.go b/internal/services/maintenance/maintenance_assignment_dynamic_scope_resource.go index 5b4282cb3bbe..399d633ace8d 100644 --- a/internal/services/maintenance/maintenance_assignment_dynamic_scope_resource.go +++ b/internal/services/maintenance/maintenance_assignment_dynamic_scope_resource.go @@ -258,11 +258,9 @@ func (MaintenanceDynamicScopeResource) Read() sdk.ResourceFunc { } if model := resp.Model; model != nil { - state.Name = id.ConfigurationAssignmentName if properties := model.Properties; properties != nil { - if properties.MaintenanceConfigurationId != nil { maintenanceConfigurationId, err := maintenanceconfigurations.ParseMaintenanceConfigurationIDInsensitively(pointer.From(properties.MaintenanceConfigurationId)) if err != nil { diff --git a/internal/services/maintenance/maintenance_assignment_virtual_machine_resource.go b/internal/services/maintenance/maintenance_assignment_virtual_machine_resource.go index ad000a214e14..95509d4b24f3 100644 --- a/internal/services/maintenance/maintenance_assignment_virtual_machine_resource.go +++ b/internal/services/maintenance/maintenance_assignment_virtual_machine_resource.go @@ -4,6 +4,7 @@ package maintenance import ( + "errors" "fmt" "strings" "time" @@ -114,7 +115,7 @@ func resourceArmMaintenanceAssignmentVirtualMachineCreate(d *pluginsdk.ResourceD err = pluginsdk.Retry(d.Timeout(pluginsdk.TimeoutCreate), func() *pluginsdk.RetryError { if _, err := client.CreateOrUpdate(ctx, id, configurationAssignment); err != nil { if strings.Contains(err.Error(), "It may take a few minutes after starting a VM for it to become available to assign to a configuration") { - return pluginsdk.RetryableError(fmt.Errorf("expected VM is available to assign to a configuration but was in pending state, retrying")) + return pluginsdk.RetryableError(errors.New("expected VM is available to assign to a configuration but was in pending state, retrying")) } return pluginsdk.NonRetryableError(fmt.Errorf("issuing creating request for %s: %+v", id, err)) } diff --git a/internal/services/maintenance/maintenance_configuration_resource.go b/internal/services/maintenance/maintenance_configuration_resource.go index 2dc3d15d62fc..6776f12e193e 100644 --- a/internal/services/maintenance/maintenance_configuration_resource.go +++ b/internal/services/maintenance/maintenance_configuration_resource.go @@ -4,6 +4,7 @@ package maintenance import ( + "errors" "fmt" "log" "regexp" @@ -264,14 +265,14 @@ func resourceMaintenanceConfigurationCreate(d *pluginsdk.ResourceData, meta inte if scope == maintenanceconfigurations.MaintenanceScopeInGuestPatch { if window == nil { - return fmt.Errorf("`window` must be specified when `scope` is `InGuestPatch`") + return errors.New("`window` must be specified when `scope` is `InGuestPatch`") } if installPatches == nil { - return fmt.Errorf("`install_patches` must be specified when `scope` is `InGuestPatch`") + return errors.New("`install_patches` must be specified when `scope` is `InGuestPatch`") } if _, ok := (*extensionProperties)["InGuestPatchMode"]; !ok { if _, ok := d.GetOk("in_guest_user_patch_mode"); !ok { - return fmt.Errorf("`in_guest_user_patch_mode` must be specified when `scope` is `InGuestPatch`") + return errors.New("`in_guest_user_patch_mode` must be specified when `scope` is `InGuestPatch`") } (*extensionProperties)["InGuestPatchMode"] = d.Get("in_guest_user_patch_mode").(string) } @@ -323,14 +324,14 @@ func resourceMaintenanceConfigurationUpdate(d *pluginsdk.ResourceData, meta inte extensionProperties := expandExtensionProperties(d.Get("properties").(map[string]interface{})) if scope == maintenanceconfigurations.MaintenanceScopeInGuestPatch { if window == nil { - return fmt.Errorf("`window` must be specified when `scope` is `InGuestPatch`") + return errors.New("`window` must be specified when `scope` is `InGuestPatch`") } if installPatches == nil { - return fmt.Errorf("`install_patches` must be specified when `scope` is `InGuestPatch`") + return errors.New("`install_patches` must be specified when `scope` is `InGuestPatch`") } if _, ok := (*extensionProperties)["InGuestPatchMode"]; !ok { if _, ok := d.GetOk("in_guest_user_patch_mode"); !ok { - return fmt.Errorf("`in_guest_user_patch_mode` must be specified when `scope` is `InGuestPatch`") + return errors.New("`in_guest_user_patch_mode` must be specified when `scope` is `InGuestPatch`") } (*extensionProperties)["InGuestPatchMode"] = d.Get("in_guest_user_patch_mode").(string) } diff --git a/internal/services/maintenance/public_maintenance_configurations_data_source.go b/internal/services/maintenance/public_maintenance_configurations_data_source.go index b980ec12ffb9..1ef7e3c0951a 100644 --- a/internal/services/maintenance/public_maintenance_configurations_data_source.go +++ b/internal/services/maintenance/public_maintenance_configurations_data_source.go @@ -5,6 +5,7 @@ package maintenance import ( "encoding/base64" + "errors" "fmt" "time" @@ -120,7 +121,7 @@ func dataSourcePublicMaintenanceConfigurationsRead(d *pluginsdk.ResourceData, me resp, err := client.List(ctx, subId) if err != nil { if response.WasNotFound(resp.HttpResponse) { - return fmt.Errorf("no Public Maintenance Configurations were found") + return errors.New("no Public Maintenance Configurations were found") } return fmt.Errorf("retrieving Public Maintenance Configurations: %+v", err) } @@ -170,7 +171,7 @@ func dataSourcePublicMaintenanceConfigurationsRead(d *pluginsdk.ResourceData, me } } if len(filteredPublicConfigs) == 0 { - return fmt.Errorf("no Public Maintenance Configurations were found") + return errors.New("no Public Maintenance Configurations were found") } if err := d.Set("configs", filteredPublicConfigs); err != nil { diff --git a/internal/services/managedapplications/managed_application_resource.go b/internal/services/managedapplications/managed_application_resource.go index 29fe059f80ce..2338528e3314 100644 --- a/internal/services/managedapplications/managed_application_resource.go +++ b/internal/services/managedapplications/managed_application_resource.go @@ -8,6 +8,7 @@ import ( "encoding/json" "fmt" "log" + "strconv" "time" "github.com/hashicorp/go-azure-helpers/lang/pointer" @@ -527,7 +528,7 @@ func flattenManagedApplicationParameterValuesValueToString(input *interface{}, l func extractParameterOrOutputValue(v interface{}) (string, error) { switch t := v.(type) { case bool: - return fmt.Sprintf("%t", v.(bool)), nil + return strconv.FormatBool(v.(bool)), nil case float64: // use precision 0 since this comes from an int return fmt.Sprintf("%.f", v.(float64)), nil diff --git a/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_rotation_policy_resource.go b/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_rotation_policy_resource.go index 72a9cda5c14c..bd0caa470a85 100644 --- a/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_rotation_policy_resource.go +++ b/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_rotation_policy_resource.go @@ -227,7 +227,6 @@ func (r KeyVaultMHSMKeyRotationPolicyResource) Delete() sdk.ResourceFunc { } func expandKeyRotationPolicy(policy MHSMKeyRotationPolicyResourceSchema) keyvault.KeyRotationPolicy { - var expiryTime *string // = nil // needs to be set to nil if not set if policy.ExpireAfter != "" { expiryTime = pointer.To(policy.ExpireAfter) diff --git a/internal/services/managedhsm/key_vault_managed_hardware_security_module_resource.go b/internal/services/managedhsm/key_vault_managed_hardware_security_module_resource.go index 6ed857c4046e..beb1bb69a433 100644 --- a/internal/services/managedhsm/key_vault_managed_hardware_security_module_resource.go +++ b/internal/services/managedhsm/key_vault_managed_hardware_security_module_resource.go @@ -471,8 +471,8 @@ func flattenMHSMNetworkAcls(acl *managedhsms.MHSMNetworkRuleSet) []interface{} { func securityDomainDownload(ctx context.Context, sdClient *kv74.HSMSecurityDomainClient, keyClient kv74.BaseClient, vaultBaseUrl string, certIds []interface{}, quorum int) (encDataStr string, err error) { var param kv74.CertificateInfoObject - param.Required = utils.Int32(int32(quorum)) - var certs []kv74.SecurityDomainJSONWebKey + param.Required = pointer.To(int32(quorum)) + certs := make([]kv74.SecurityDomainJSONWebKey, 0, len(certIds)) for _, certID := range certIds { certIDStr, ok := certID.(string) if !ok { @@ -490,12 +490,12 @@ func securityDomainDownload(ctx context.Context, sdClient *kv74.HSMSecurityDomai return "", fmt.Errorf("got nil key for %s", certID) } cert := kv74.SecurityDomainJSONWebKey{ - Kty: pointer.FromString("RSA"), + Kty: pointer.To("RSA"), KeyOps: &[]string{""}, - Alg: pointer.FromString("RSA-OAEP-256"), + Alg: pointer.To("RSA-OAEP-256"), } if certRes.Policy != nil && certRes.Policy.KeyProperties != nil { - cert.Kty = pointer.FromString(string(certRes.Policy.KeyProperties.KeyType)) + cert.Kty = pointer.To(string(certRes.Policy.KeyProperties.KeyType)) } x5c := "" if contents := certRes.Cer; contents != nil { @@ -506,7 +506,7 @@ func securityDomainDownload(ctx context.Context, sdClient *kv74.HSMSecurityDomai sum256 := sha256.Sum256([]byte(x5c)) s256Dst := make([]byte, base64.StdEncoding.EncodedLen(len(sum256))) base64.URLEncoding.Encode(s256Dst, sum256[:]) - cert.X5tS256 = pointer.FromString(string(s256Dst)) + cert.X5tS256 = pointer.To(string(s256Dst)) certs = append(certs, cert) } param.Certificates = &certs diff --git a/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_assignment_resource.go b/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_assignment_resource.go index 0c53b53744ba..224dec2f5007 100644 --- a/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_assignment_resource.go +++ b/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_assignment_resource.go @@ -192,9 +192,9 @@ func (r KeyVaultManagedHSMRoleAssignmentResource) Create() sdk.ResourceFunc { var param keyvault.RoleAssignmentCreateParameters param.Properties = &keyvault.RoleAssignmentProperties{ - PrincipalID: pointer.FromString(config.PrincipalId), + PrincipalID: pointer.To(config.PrincipalId), // the role definition id may have '/' prefix, but the api doesn't accept it - RoleDefinitionID: pointer.FromString(strings.TrimPrefix(config.RoleDefinitionId, "/")), + RoleDefinitionID: pointer.To(strings.TrimPrefix(config.RoleDefinitionId, "/")), } //nolint:misspell diff --git a/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_definition_resource.go b/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_definition_resource.go index ac2081e7f591..c2b712c4d3b7 100644 --- a/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_definition_resource.go +++ b/internal/services/managedhsm/key_vault_managed_hardware_security_module_role_definition_resource.go @@ -501,7 +501,7 @@ func (r KeyVaultMHSMRoleDefinitionResource) IDValidationFunc() pluginsdk.SchemaV } func expandKeyVaultMHSMRolePermissions(perms []Permission) *[]keyvault.Permission { - var res []keyvault.Permission + res := make([]keyvault.Permission, 0, len(perms)) for _, perm := range perms { var dataActions, notDataActions = make([]keyvault.DataAction, 0), make([]keyvault.DataAction, 0) for _, data := range perm.DataActions { @@ -526,7 +526,7 @@ func flattenKeyVaultMHSMRolePermission(perms *[]keyvault.Permission) []Permissio return make([]Permission, 0) } - var res []Permission + res := make([]Permission, 0, len(*perms)) for _, perm := range *perms { var data, notData []string for _, item := range pointer.From(perm.DataActions) { diff --git a/internal/services/managedidentity/client/client_gen.go b/internal/services/managedidentity/client/client_gen.go index 0b429e5afdfe..34ae56ca3242 100644 --- a/internal/services/managedidentity/client/client_gen.go +++ b/internal/services/managedidentity/client/client_gen.go @@ -13,7 +13,6 @@ type AutoClient struct { } func NewClient(o *common.ClientOptions) (*AutoClient, error) { - v20230131Client, err := managedidentityV20230131.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { o.Configure(c, o.Authorizers.ResourceManager) }) diff --git a/internal/services/managedidentity/user_assigned_identity_resource_gen.go b/internal/services/managedidentity/user_assigned_identity_resource_gen.go index 25fba79c2044..00b468069f24 100644 --- a/internal/services/managedidentity/user_assigned_identity_resource_gen.go +++ b/internal/services/managedidentity/user_assigned_identity_resource_gen.go @@ -247,7 +247,6 @@ func (r UserAssignedIdentityResource) mapIdentityUpdateToUserAssignedIdentityRes } func (r UserAssignedIdentityResource) mapUserAssignedIdentityResourceSchemaToUserAssignedIdentityProperties(input UserAssignedIdentityResourceSchema, output *managedidentities.UserAssignedIdentityProperties) error { - return nil } diff --git a/internal/services/managementgroup/management_group_resource_test.go b/internal/services/managementgroup/management_group_resource_test.go index 6fd20a90c082..04ffa80f20bb 100644 --- a/internal/services/managementgroup/management_group_resource_test.go +++ b/internal/services/managementgroup/management_group_resource_test.go @@ -191,7 +191,7 @@ func (ManagementGroupResource) Exists(ctx context.Context, clients *clients.Clie return nil, err } resp, err := clients.ManagementGroups.GroupsClient.Get(ctx, *id, managementgroups.GetOperationOptions{ - CacheControl: pointer.FromString("no-cache"), + CacheControl: pointer.To("no-cache"), Expand: pointer.To(managementgroups.ExpandChildren), Recurse: pointer.FromBool(false), }) diff --git a/internal/services/managementgroup/subscription_association_resource_test.go b/internal/services/managementgroup/subscription_association_resource_test.go index 4f5b799ab927..d0d20b345881 100644 --- a/internal/services/managementgroup/subscription_association_resource_test.go +++ b/internal/services/managementgroup/subscription_association_resource_test.go @@ -116,7 +116,7 @@ func (r ManagementGroupSubscriptionAssociation) Exists(ctx context.Context, clie } resp, err := client.ManagementGroups.GroupsClient.Get(ctx, commonids.NewManagementGroupID(id.GroupId), managementgroups.GetOperationOptions{ - CacheControl: pointer.FromString("no-cache"), + CacheControl: pointer.To("no-cache"), Expand: pointer.To(managementgroups.ExpandChildren), Recurse: pointer.FromBool(false), }) diff --git a/internal/services/mobilenetwork/mobile_network_service_data_source.go b/internal/services/mobilenetwork/mobile_network_service_data_source.go index 09e389f80901..366e36dee6b3 100644 --- a/internal/services/mobilenetwork/mobile_network_service_data_source.go +++ b/internal/services/mobilenetwork/mobile_network_service_data_source.go @@ -332,8 +332,7 @@ func (r ServiceDataSource) Read() sdk.ResourceFunc { } func flattenPccRuleConfigurationDataSourceModel(inputList []service.PccRuleConfiguration) []ServiceDataSourcePccRuleConfigurationModel { - var outputList []ServiceDataSourcePccRuleConfigurationModel - + outputList := make([]ServiceDataSourcePccRuleConfigurationModel, 0, len(inputList)) for _, input := range inputList { output := ServiceDataSourcePccRuleConfigurationModel{ RuleName: input.RuleName, diff --git a/internal/services/mobilenetwork/mobile_network_service_resource.go b/internal/services/mobilenetwork/mobile_network_service_resource.go index 2e66d27be858..8bcd515cb836 100644 --- a/internal/services/mobilenetwork/mobile_network_service_resource.go +++ b/internal/services/mobilenetwork/mobile_network_service_resource.go @@ -511,7 +511,7 @@ func (r ServiceResource) Delete() sdk.ResourceFunc { } func expandPccRuleConfigurationResourceModel(inputList []ServiceResourcePccRuleConfigurationModel) []service.PccRuleConfiguration { - var outputList []service.PccRuleConfiguration + outputList := make([]service.PccRuleConfiguration, 0, len(inputList)) for _, v := range inputList { input := v output := service.PccRuleConfiguration{ @@ -524,11 +524,8 @@ func expandPccRuleConfigurationResourceModel(inputList []ServiceResourcePccRuleC trafficControlValue = service.TrafficControlPermissionEnabled } output.TrafficControl = &trafficControlValue - output.RuleQosPolicy = expandPccRuleQosPolicyResourceModel(input.RuleQosPolicy) - output.ServiceDataFlowTemplates = expandServiceDataFlowTemplateResourceModel(input.ServiceDataFlowTemplates) - outputList = append(outputList, output) } @@ -600,8 +597,7 @@ func expandQosPolicyResourceModel(inputList []ServiceResourceQosPolicyModel) *se } func flattenPccRuleConfigurationModel(inputList []service.PccRuleConfiguration) []ServiceResourcePccRuleConfigurationModel { - var outputList []ServiceResourcePccRuleConfigurationModel - + outputList := make([]ServiceResourcePccRuleConfigurationModel, 0, len(inputList)) for _, input := range inputList { output := ServiceResourcePccRuleConfigurationModel{ RuleName: input.RuleName, @@ -655,11 +651,11 @@ func flattenPccRuleQosPolicyResourceModel(input *service.PccRuleQosPolicy) []Ser } func flattenServiceDataFlowTemplateResourceModel(inputList *[]service.ServiceDataFlowTemplate) []ServiceResourceServiceDataFlowTemplateModel { - var outputList []ServiceResourceServiceDataFlowTemplateModel if inputList == nil { - return outputList + return []ServiceResourceServiceDataFlowTemplateModel{} } + outputList := make([]ServiceResourceServiceDataFlowTemplateModel, 0, len(*inputList)) for _, input := range *inputList { output := ServiceResourceServiceDataFlowTemplateModel{ Direction: string(input.Direction), diff --git a/internal/services/mobilenetwork/mobile_network_sim_policy_data_source.go b/internal/services/mobilenetwork/mobile_network_sim_policy_data_source.go index fa9a6c327cc6..73cb325bff59 100644 --- a/internal/services/mobilenetwork/mobile_network_sim_policy_data_source.go +++ b/internal/services/mobilenetwork/mobile_network_sim_policy_data_source.go @@ -273,7 +273,6 @@ func (r SimPolicyDataSource) Read() sdk.ResourceFunc { if model.Tags != nil { state.Tags = *model.Tags } - } metadata.SetID(id) diff --git a/internal/services/mobilenetwork/mobile_network_sim_policy_resource.go b/internal/services/mobilenetwork/mobile_network_sim_policy_resource.go index 356d4cb223bb..353bddd7dd4d 100644 --- a/internal/services/mobilenetwork/mobile_network_sim_policy_resource.go +++ b/internal/services/mobilenetwork/mobile_network_sim_policy_resource.go @@ -362,7 +362,6 @@ func (r SimPolicyResource) Update() sdk.ResourceFunc { if metadata.ResourceData.HasChange("default_slice") { model.Properties.DefaultSlice = simpolicy.SliceResourceId{Id: plan.DefaultSliceId} - } if metadata.ResourceData.HasChange("registration_timer_in_seconds") { @@ -466,7 +465,7 @@ func (r SimPolicyResource) Delete() sdk.ResourceFunc { } func expandSliceConfigurationResourceModel(inputList []SliceConfigurationResourceModel) []simpolicy.SliceConfiguration { - var outputList []simpolicy.SliceConfiguration + outputList := make([]simpolicy.SliceConfiguration, 0, len(inputList)) for _, v := range inputList { input := v output := simpolicy.SliceConfiguration{ @@ -490,7 +489,7 @@ func expandSliceConfigurationResourceModel(inputList []SliceConfigurationResourc } func expandDataNetworkConfigurationResourceModel(inputList []DataNetworkConfigurationResourceModel) []simpolicy.DataNetworkConfiguration { - var outputList []simpolicy.DataNetworkConfiguration + outputList := make([]simpolicy.DataNetworkConfiguration, 0, len(inputList)) for _, v := range inputList { input := v @@ -523,7 +522,7 @@ func expandDataNetworkConfigurationResourceModel(inputList []DataNetworkConfigur } func expandSimPolicyAdditionalAllowedSessionTypeResource(inputList []string) *[]simpolicy.PduSessionType { - var outputList []simpolicy.PduSessionType + outputList := make([]simpolicy.PduSessionType, 0, len(inputList)) for _, v := range inputList { outputList = append(outputList, simpolicy.PduSessionType(v)) } @@ -532,7 +531,7 @@ func expandSimPolicyAdditionalAllowedSessionTypeResource(inputList []string) *[] } func expandServiceResourceIdResourceModel(inputList []string) []simpolicy.ServiceResourceId { - var outputList []simpolicy.ServiceResourceId + outputList := make([]simpolicy.ServiceResourceId, 0, len(inputList)) for _, v := range inputList { input := v output := simpolicy.ServiceResourceId{ diff --git a/internal/services/mongocluster/client/client.go b/internal/services/mongocluster/client/client.go index 423033b4201e..7158dfe4ff06 100644 --- a/internal/services/mongocluster/client/client.go +++ b/internal/services/mongocluster/client/client.go @@ -15,7 +15,6 @@ type Client struct { } func NewClient(o *common.ClientOptions) (*Client, error) { - mongoClustersClient, err := mongoclusters.NewMongoClustersClientWithBaseURI(o.Environment.ResourceManager) if err != nil { return nil, fmt.Errorf("building MongoClusters client: %+v", err) diff --git a/internal/services/monitor/monitor_action_group_resource.go b/internal/services/monitor/monitor_action_group_resource.go index 3080e643f253..bb7de7fb5eca 100644 --- a/internal/services/monitor/monitor_action_group_resource.go +++ b/internal/services/monitor/monitor_action_group_resource.go @@ -538,7 +538,6 @@ func resourceMonitorActionGroupRead(d *pluginsdk.ResourceData, meta interface{}) d.Set("resource_group_name", id.ResourceGroupName) if model := resp.Model; model != nil { - d.Set("location", location.Normalize(model.Location)) if props := model.Properties; props != nil { diff --git a/internal/services/monitor/monitor_autoscale_setting_resource.go b/internal/services/monitor/monitor_autoscale_setting_resource.go index 2766565528a9..17c7a622383b 100644 --- a/internal/services/monitor/monitor_autoscale_setting_resource.go +++ b/internal/services/monitor/monitor_autoscale_setting_resource.go @@ -546,7 +546,6 @@ func resourceMonitorAutoScaleSettingRead(d *pluginsdk.ResourceData, meta interfa if err = d.Set("tags", utils.FlattenPtrMapStringString(tagMap)); err != nil { return err } - } return nil } @@ -877,7 +876,6 @@ func flattenAzureRmMonitorAutoScaleSettingPredictive(input *autoscalesettings.Pr } func flattenAzureRmMonitorAutoScaleSettingCapacity(input autoscalesettings.ScaleCapacity) ([]interface{}, error) { - result := make(map[string]interface{}) min, err := strconv.Atoi(input.Minimum) @@ -1062,7 +1060,6 @@ func flattenAzureRmMonitorAutoScaleSettingNotification(notifications *[]autoscal if webHookProps := v.Properties; webHookProps != nil { for key, value := range *v.Properties { props[key] = value - } hook["properties"] = props webhooks = append(webhooks, hook) @@ -1085,7 +1082,6 @@ func flattenAzureRmMonitorAutoScaleSettingRulesDimensions(dimensions *[]autoscal } for _, dimension := range *dimensions { - results = append(results, map[string]interface{}{ "name": dimension.DimensionName, "operator": string(dimension.Operator), diff --git a/internal/services/monitor/monitor_metric_alert_resource.go b/internal/services/monitor/monitor_metric_alert_resource.go index 6b22a12180fc..def5222be7fd 100644 --- a/internal/services/monitor/monitor_metric_alert_resource.go +++ b/internal/services/monitor/monitor_metric_alert_resource.go @@ -435,7 +435,6 @@ func resourceMonitorMetricAlertCreateUpdate(d *pluginsdk.ResourceData, meta inte return fmt.Errorf("unexpected nil properties of Monitor %s", id) } _, isLegacy = existing.Model.Properties.Criteria.(metricalerts.MetricAlertSingleResourceMultipleMetricCriteria) - } criteria, err := expandMonitorMetricAlertCriteria(d, isLegacy) diff --git a/internal/services/monitor/monitor_private_link_scope_resource.go b/internal/services/monitor/monitor_private_link_scope_resource.go index 611bd5b4b7d5..e7a9c83202ac 100644 --- a/internal/services/monitor/monitor_private_link_scope_resource.go +++ b/internal/services/monitor/monitor_private_link_scope_resource.go @@ -148,7 +148,6 @@ func resourceMonitorPrivateLinkScopeRead(d *pluginsdk.ResourceData, meta interfa props := model.Properties d.Set("ingestion_access_mode", string(props.AccessModeSettings.IngestionAccessMode)) d.Set("query_access_mode", string(props.AccessModeSettings.QueryAccessMode)) - } return nil diff --git a/internal/services/monitor/monitor_scheduled_query_rules_alert_data_source.go b/internal/services/monitor/monitor_scheduled_query_rules_alert_data_source.go index 07ce3608d1dd..21ddf2c9dddf 100644 --- a/internal/services/monitor/monitor_scheduled_query_rules_alert_data_source.go +++ b/internal/services/monitor/monitor_scheduled_query_rules_alert_data_source.go @@ -214,7 +214,6 @@ func dataSourceMonitorScheduledQueryRulesAlertRead(d *pluginsdk.ResourceData, me if err = d.Set("tags", utils.FlattenPtrMapStringString(model.Tags)); err != nil { return err } - } return nil diff --git a/internal/services/monitor/monitor_scheduled_query_rules_alert_v2_resource.go b/internal/services/monitor/monitor_scheduled_query_rules_alert_v2_resource.go index dd565a2ce39f..ed827ff240d7 100644 --- a/internal/services/monitor/monitor_scheduled_query_rules_alert_v2_resource.go +++ b/internal/services/monitor/monitor_scheduled_query_rules_alert_v2_resource.go @@ -768,7 +768,7 @@ func expandScheduledQueryRulesAlertV2ActionsModel(inputList []ScheduledQueryRule func expandScheduledQueryRulesAlertV2CriteriaModel(inputList []ScheduledQueryRulesAlertV2CriteriaModel) *scheduledqueryrules.ScheduledQueryRuleCriteria { output := scheduledqueryrules.ScheduledQueryRuleCriteria{} - var outputList []scheduledqueryrules.Condition + outputList := make([]scheduledqueryrules.Condition, 0, len(inputList)) for _, v := range inputList { input := v condition := scheduledqueryrules.Condition{ @@ -799,7 +799,7 @@ func expandScheduledQueryRulesAlertV2CriteriaModel(inputList []ScheduledQueryRul } func expandScheduledQueryRulesAlertV2DimensionModel(inputList []ScheduledQueryRulesAlertV2DimensionModel) *[]scheduledqueryrules.Dimension { - var outputList []scheduledqueryrules.Dimension + outputList := make([]scheduledqueryrules.Dimension, 0, len(inputList)) for _, v := range inputList { input := v output := scheduledqueryrules.Dimension{ @@ -848,17 +848,12 @@ func flattenScheduledQueryRulesAlertV2ActionsModel(input *scheduledqueryrules.Ac } func flattenScheduledQueryRulesAlertV2CriteriaModel(input *scheduledqueryrules.ScheduledQueryRuleCriteria) []ScheduledQueryRulesAlertV2CriteriaModel { - var outputList []ScheduledQueryRulesAlertV2CriteriaModel - if input == nil { - return outputList + if input == nil || input.AllOf == nil { + return []ScheduledQueryRulesAlertV2CriteriaModel{} } - inputList := input.AllOf - if inputList == nil { - return outputList - } - - for _, v := range *inputList { + outputList := make([]ScheduledQueryRulesAlertV2CriteriaModel, 0, len(*input.AllOf)) + for _, v := range *input.AllOf { output := ScheduledQueryRulesAlertV2CriteriaModel{} output.Dimensions = flattenScheduledQueryRulesAlertV2DimensionModel(v.Dimensions) @@ -895,11 +890,11 @@ func flattenScheduledQueryRulesAlertV2CriteriaModel(input *scheduledqueryrules.S } func flattenScheduledQueryRulesAlertV2DimensionModel(inputList *[]scheduledqueryrules.Dimension) []ScheduledQueryRulesAlertV2DimensionModel { - var outputList []ScheduledQueryRulesAlertV2DimensionModel if inputList == nil { - return outputList + return []ScheduledQueryRulesAlertV2DimensionModel{} } + outputList := make([]ScheduledQueryRulesAlertV2DimensionModel, 0, len(*inputList)) for _, input := range *inputList { output := ScheduledQueryRulesAlertV2DimensionModel{ Name: input.Name, diff --git a/internal/services/mssql/mssql_failover_group_resource.go b/internal/services/mssql/mssql_failover_group_resource.go index c1fbacd33a51..abb919a51848 100644 --- a/internal/services/mssql/mssql_failover_group_resource.go +++ b/internal/services/mssql/mssql_failover_group_resource.go @@ -324,7 +324,6 @@ func (r MsSqlFailoverGroupResource) Read() sdk.ResourceFunc { } if existing.Model != nil { - model.Tags = pointer.From(existing.Model.Tags) if props := existing.Model.Properties; props != nil { @@ -343,7 +342,6 @@ func (r MsSqlFailoverGroupResource) Read() sdk.ResourceFunc { }} model.ReadWriteEndpointFailurePolicy[0].GraceMinutes = pointer.From(props.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes) - } } @@ -400,7 +398,7 @@ func (r MsSqlFailoverGroupResource) flattenPartnerServers(input []failovergroups } func (r MsSqlFailoverGroupResource) expandPartnerServers(input []PartnerServerModel) []failovergroups.PartnerInfo { - var partnerServers []failovergroups.PartnerInfo + partnerServers := make([]failovergroups.PartnerInfo, 0, len(input)) if input == nil { return partnerServers } diff --git a/internal/services/mssql/mssql_server_transparent_data_encryption_resource.go b/internal/services/mssql/mssql_server_transparent_data_encryption_resource.go index 72a3e8710987..6dfafd5a8aba 100644 --- a/internal/services/mssql/mssql_server_transparent_data_encryption_resource.go +++ b/internal/services/mssql/mssql_server_transparent_data_encryption_resource.go @@ -272,7 +272,6 @@ func resourceMsSqlTransparentDataEncryptionRead(d *pluginsdk.ResourceData, meta hsmKey = keyId } else { keyVaultKeyId = keyId - } } diff --git a/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go b/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go index 2a556d4c7407..af63f92cadc0 100644 --- a/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go +++ b/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go @@ -307,7 +307,6 @@ func (r MsSqlVirtualMachineAvailabilityGroupListenerResource) Read() sdk.Resourc return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.MSSQL.VirtualMachinesAvailabilityGroupListenersClient id, err := availabilitygrouplisteners.ParseAvailabilityGroupListenerID(metadata.ResourceData.Id()) @@ -330,7 +329,6 @@ func (r MsSqlVirtualMachineAvailabilityGroupListenerResource) Read() sdk.Resourc if model := resp.Model; model != nil { if props := model.Properties; props != nil { - state.AvailabilityGroupName = pointer.From(props.AvailabilityGroupName) state.Port = pointer.From(props.Port) @@ -348,7 +346,6 @@ func (r MsSqlVirtualMachineAvailabilityGroupListenerResource) Read() sdk.Resourc if props.AvailabilityGroupConfiguration != nil { if props.AvailabilityGroupConfiguration.Replicas != nil { - replicas, err := flattenMsSqlVirtualMachineAvailabilityGroupListenerReplicas(props.AvailabilityGroupConfiguration.Replicas, id.SubscriptionId) if err != nil { return fmt.Errorf("setting `replica`: %+v", err) @@ -387,7 +384,6 @@ func expandMsSqlVirtualMachineAvailabilityGroupListenerLoadBalancerConfiguration results := make([]availabilitygrouplisteners.LoadBalancerConfiguration, 0) for _, lb := range lbConfigs { - lbConfig := availabilitygrouplisteners.LoadBalancerConfiguration{ ProbePort: pointer.To(lb.ProbePort), } @@ -426,7 +422,6 @@ func expandMsSqlVirtualMachineAvailabilityGroupListenerMultiSubnetIpConfiguratio results := make([]availabilitygrouplisteners.MultiSubnetIPConfiguration, 0) for _, item := range multiSubnetIpConfiguration { - config := availabilitygrouplisteners.MultiSubnetIPConfiguration{ SqlVirtualMachineInstance: item.SqlVirtualMachineId, } @@ -565,7 +560,6 @@ func flattenMsSqlVirtualMachineAvailabilityGroupListenerReplicas(input *[]availa } for _, replica := range *input { - sqlVirtualMachineInstanceId := "" if replica.SqlVirtualMachineInstanceId != nil { parsedId, err := sqlvirtualmachines.ParseSqlVirtualMachineIDInsensitively(*replica.SqlVirtualMachineInstanceId) diff --git a/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource_test.go b/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource_test.go index c0df09c16e81..b2b14833741d 100644 --- a/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource_test.go +++ b/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource_test.go @@ -65,7 +65,6 @@ func TestAccMsSqlVirtualMachineAvailabilityGroupListener_multiSubnetIpConfigurat } func (MsSqlVirtualMachineAvailabilityGroupListenerResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := availabilitygrouplisteners.ParseAvailabilityGroupListenerID(state.ID) if err != nil { return nil, err diff --git a/internal/services/mssql/mssql_virtual_machine_group_resource.go b/internal/services/mssql/mssql_virtual_machine_group_resource.go index 88428e44d930..d5ea85dc3c5a 100644 --- a/internal/services/mssql/mssql_virtual_machine_group_resource.go +++ b/internal/services/mssql/mssql_virtual_machine_group_resource.go @@ -215,7 +215,6 @@ func (r MsSqlVirtualMachineGroupResource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.MSSQL.VirtualMachineGroupsClient id, err := sqlvirtualmachinegroups.ParseSqlVirtualMachineGroupID(metadata.ResourceData.Id()) @@ -238,7 +237,6 @@ func (r MsSqlVirtualMachineGroupResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if props := model.Properties; props != nil { - state.SqlImageOffer = pointer.From(props.SqlImageOffer) state.SqlImageSku = string(pointer.From(props.SqlImageSku)) @@ -251,7 +249,6 @@ func (r MsSqlVirtualMachineGroupResource) Read() sdk.ResourceFunc { storageAccountPrimaryKey = oldModel.WsfcDomainProfile[0].StorageAccountPrimaryKey } state.WsfcDomainProfile = flattenMsSqlVirtualMachineGroupWsfcDomainProfile(props.WsfcDomainProfile, storageAccountPrimaryKey) - } state.Location = location.Normalize(model.Location) diff --git a/internal/services/mssqlmanagedinstance/client/client.go b/internal/services/mssqlmanagedinstance/client/client.go index fd10a31ac330..dce0f0881c1d 100644 --- a/internal/services/mssqlmanagedinstance/client/client.go +++ b/internal/services/mssqlmanagedinstance/client/client.go @@ -38,7 +38,6 @@ type Client struct { } func NewClient(o *common.ClientOptions) (*Client, error) { - managedDatabasesClient, err := manageddatabases.NewManagedDatabasesClientWithBaseURI(o.Environment.ResourceManager) if err != nil { return nil, fmt.Errorf("building Managed Databases Client: %+v", err) diff --git a/internal/services/mssqlmanagedinstance/mssql_managed_database_resource.go b/internal/services/mssqlmanagedinstance/mssql_managed_database_resource.go index eb0536952721..6f49e1676054 100644 --- a/internal/services/mssqlmanagedinstance/mssql_managed_database_resource.go +++ b/internal/services/mssqlmanagedinstance/mssql_managed_database_resource.go @@ -378,7 +378,6 @@ func expandLongTermRetentionPolicy(ltrPolicy []LongTermRetentionPolicy) managedi } func flattenLongTermRetentionPolicy(ltrPolicy managedinstancelongtermretentionpolicies.ManagedInstanceLongTermRetentionPolicyProperties) []LongTermRetentionPolicy { - ltrModel := LongTermRetentionPolicy{ WeeklyRetention: pointer.From(ltrPolicy.WeeklyRetention), MonthlyRetention: pointer.From(ltrPolicy.MonthlyRetention), diff --git a/internal/services/mssqlmanagedinstance/mssql_managed_instance_active_directory_administrator_resource.go b/internal/services/mssqlmanagedinstance/mssql_managed_instance_active_directory_administrator_resource.go index edad0b292045..2561e3239add 100644 --- a/internal/services/mssqlmanagedinstance/mssql_managed_instance_active_directory_administrator_resource.go +++ b/internal/services/mssqlmanagedinstance/mssql_managed_instance_active_directory_administrator_resource.go @@ -237,12 +237,10 @@ func (r MsSqlManagedInstanceActiveDirectoryAdministratorResource) Read() sdk.Res } if result.Model != nil { - if props := result.Model.Properties; props != nil { model.LoginUsername = props.Login model.ObjectId = props.Sid model.TenantId = pointer.From(props.TenantId) - } } diff --git a/internal/services/mssqlmanagedinstance/mssql_managed_instance_data_source.go b/internal/services/mssqlmanagedinstance/mssql_managed_instance_data_source.go index 23e6de1799f9..eb3022ff3b8c 100644 --- a/internal/services/mssqlmanagedinstance/mssql_managed_instance_data_source.go +++ b/internal/services/mssqlmanagedinstance/mssql_managed_instance_data_source.go @@ -215,7 +215,6 @@ func (d MsSqlManagedInstanceDataSource) Read() sdk.ResourceFunc { model.SubnetId = pointer.From(props.SubnetId) model.TimezoneId = pointer.From(props.TimezoneId) model.VCores = pointer.From(props.VCores) - } metadata.SetID(id) diff --git a/internal/services/mssqlmanagedinstance/mssql_managed_instance_resource.go b/internal/services/mssqlmanagedinstance/mssql_managed_instance_resource.go index 54414e474f77..1291746639e0 100644 --- a/internal/services/mssqlmanagedinstance/mssql_managed_instance_resource.go +++ b/internal/services/mssqlmanagedinstance/mssql_managed_instance_resource.go @@ -484,7 +484,6 @@ func (r MsSqlManagedInstanceResource) Read() sdk.ResourceFunc { model := MsSqlManagedInstanceModel{} if existing.Model != nil { - model = MsSqlManagedInstanceModel{ Name: id.ManagedInstanceName, Location: location.NormalizeNilable(&existing.Model.Location), diff --git a/internal/services/mssqlmanagedinstance/mssql_managed_instance_security_alert_policy_resource.go b/internal/services/mssqlmanagedinstance/mssql_managed_instance_security_alert_policy_resource.go index 0b16c60d4073..badadb073910 100644 --- a/internal/services/mssqlmanagedinstance/mssql_managed_instance_security_alert_policy_resource.go +++ b/internal/services/mssqlmanagedinstance/mssql_managed_instance_security_alert_policy_resource.go @@ -269,7 +269,6 @@ func resourceMsSqlManagedInstanceSecurityAlertPolicyRead(d *pluginsdk.ResourceDa d.Set("managed_instance_name", id.ManagedInstanceName) if result.Model != nil { - if props := result.Model.Properties; props != nil { d.Set("enabled", props.State == managedserversecurityalertpolicies.SecurityAlertsPolicyStateEnabled) diff --git a/internal/services/mssqlmanagedinstance/mssql_managed_instance_transparent_data_encryption_resource.go b/internal/services/mssqlmanagedinstance/mssql_managed_instance_transparent_data_encryption_resource.go index 5ba21d6b501d..4e75105ac7bd 100644 --- a/internal/services/mssqlmanagedinstance/mssql_managed_instance_transparent_data_encryption_resource.go +++ b/internal/services/mssqlmanagedinstance/mssql_managed_instance_transparent_data_encryption_resource.go @@ -150,7 +150,6 @@ func resourceMsSqlManagedInstanceTransparentDataEncryptionCreateUpdate(d *plugin if err != nil { return fmt.Errorf("creating/updating managed instance key for %s: %+v", managedInstanceId, err) } - } encryptionProtectorObject := managedinstanceencryptionprotectors.ManagedInstanceEncryptionProtector{ @@ -195,7 +194,6 @@ func resourceMsSqlManagedInstanceTransparentDataEncryptionRead(d *pluginsdk.Reso d.Set("managed_instance_id", managedInstanceId.ID()) if resp.Model != nil && resp.Model.Properties != nil { - log.Printf("[INFO] Encryption protector key type is %s", resp.Model.Properties.ServerKeyType) keyVaultKeyId := "" diff --git a/internal/services/netapp/netapp_account_encryption_data_source.go b/internal/services/netapp/netapp_account_encryption_data_source.go index 0cdd91253a2b..74f72e5aa6d8 100644 --- a/internal/services/netapp/netapp_account_encryption_data_source.go +++ b/internal/services/netapp/netapp_account_encryption_data_source.go @@ -74,7 +74,6 @@ func (r NetAppAccountEncryptionDataSource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.AccountClient var state netAppModels.NetAppAccountEncryptionDataSourceModel @@ -111,13 +110,11 @@ func (r NetAppAccountEncryptionDataSource) Read() sdk.ResourceFunc { } if len(anfAccountIdentityFlattened) > 0 { - if anfAccountIdentityFlattened[0].Type == identity.TypeSystemAssigned { state.SystemAssignedIdentityPrincipalID = anfAccountIdentityFlattened[0].PrincipalId } if anfAccountIdentityFlattened[0].Type == identity.TypeUserAssigned { - if len(anfAccountIdentityFlattened[0].IdentityIds) > 0 { state.UserAssignedIdentityID = anfAccountIdentityFlattened[0].IdentityIds[0] } diff --git a/internal/services/netapp/netapp_account_encryption_resource.go b/internal/services/netapp/netapp_account_encryption_resource.go index bc2f11452617..5d44c949fc61 100644 --- a/internal/services/netapp/netapp_account_encryption_resource.go +++ b/internal/services/netapp/netapp_account_encryption_resource.go @@ -113,7 +113,6 @@ func (r NetAppAccountEncryptionResource) Create() sdk.ResourceFunc { if !response.WasNotFound(existing.HttpResponse) { if existing.Model.Properties.Encryption != nil && existing.Model.Properties.Encryption.KeySource != nil && pointer.From(existing.Model.Properties.Encryption.KeySource) == netappaccounts.KeySourceMicrosoftPointKeyVault { - return tf.ImportAsExistsError(r.ResourceType(), accountID.ID()) } } @@ -192,7 +191,6 @@ func (r NetAppAccountEncryptionResource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.AccountClient id, err := netappaccounts.ParseNetAppAccountID((metadata.ResourceData.Id())) @@ -234,7 +232,6 @@ func (r NetAppAccountEncryptionResource) Read() sdk.ResourceFunc { } if len(anfAccountIdentityFlattened) > 0 { - if anfAccountIdentityFlattened[0].Type == identity.TypeSystemAssigned { model.SystemAssignedIdentityPrincipalID = anfAccountIdentityFlattened[0].PrincipalId } diff --git a/internal/services/netapp/netapp_account_resource.go b/internal/services/netapp/netapp_account_resource.go index ebc4204b994d..fcd5105a7988 100644 --- a/internal/services/netapp/netapp_account_resource.go +++ b/internal/services/netapp/netapp_account_resource.go @@ -208,7 +208,6 @@ func resourceNetAppAccountCreate(d *pluginsdk.ResourceData, meta interface{}) er anfAccountIdentity, ok := anfAccountIdentityRaw.([]interface{}) if ok && len(anfAccountIdentity) > 0 { - anfAccountIdentityExpanded, err := identity.ExpandLegacySystemAndUserAssignedMap(anfAccountIdentity) if err != nil { return err diff --git a/internal/services/netapp/netapp_volume_group_sap_hana_data_source.go b/internal/services/netapp/netapp_volume_group_sap_hana_data_source.go index a76fde2697e1..e8f03834b88c 100644 --- a/internal/services/netapp/netapp_volume_group_sap_hana_data_source.go +++ b/internal/services/netapp/netapp_volume_group_sap_hana_data_source.go @@ -237,7 +237,6 @@ func (r NetAppVolumeGroupSapHanaDataSource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.VolumeGroupClient var state netAppModels.NetAppVolumeGroupSapHanaDataSourceModel diff --git a/internal/services/netapp/netapp_volume_group_sap_hana_resource.go b/internal/services/netapp/netapp_volume_group_sap_hana_resource.go index eb97dbe2839a..4f7a0ddd9865 100644 --- a/internal/services/netapp/netapp_volume_group_sap_hana_resource.go +++ b/internal/services/netapp/netapp_volume_group_sap_hana_resource.go @@ -336,7 +336,6 @@ func (r NetAppVolumeGroupSapHanaResource) Create() sdk.ResourceFunc { if volumeCrr.Properties.DataProtection != nil && volumeCrr.Properties.DataProtection.Replication != nil && strings.EqualFold(string(pointer.From(volumeCrr.Properties.DataProtection.Replication.EndpointType)), string(volumegroups.EndpointTypeDst)) { - // Modify volumeType as data protection type on main volumeList // so it gets created correctly as data protection volume (pointer.From(volumeList))[i].Properties.VolumeType = utils.String("DataProtection") @@ -375,7 +374,6 @@ func (r NetAppVolumeGroupSapHanaResource) Create() sdk.ResourceFunc { if volumeCrr.Properties.DataProtection != nil && volumeCrr.Properties.DataProtection.Replication != nil && strings.EqualFold(string(pointer.From(volumeCrr.Properties.DataProtection.Replication.EndpointType)), string(volumegroups.EndpointTypeDst)) { - capacityPoolId, err := capacitypools.ParseCapacityPoolID(pointer.From(volumeCrr.Properties.CapacityPoolResourceId)) if err != nil { return err @@ -438,10 +436,8 @@ func (r NetAppVolumeGroupSapHanaResource) Update() sdk.ResourceFunc { metadata.Logger.Infof("Updating %s", id) if metadata.ResourceData.HasChange("volume") { - // Iterating over each volume and performing individual patch for i := 0; i < metadata.ResourceData.Get("volume.#").(int); i++ { - // Checking if individual volume has a change volumeItem := fmt.Sprintf("volume.%v", i) @@ -451,7 +447,6 @@ func (r NetAppVolumeGroupSapHanaResource) Update() sdk.ResourceFunc { } if metadata.ResourceData.HasChange(volumeItem) { - volumeId := volumes.NewVolumeID(id.SubscriptionId, id.ResourceGroupName, id.NetAppAccountName, @@ -504,7 +499,6 @@ func (r NetAppVolumeGroupSapHanaResource) Update() sdk.ResourceFunc { dataProtectionReplication.Replication != nil && dataProtectionReplication.Replication.EndpointType != nil && strings.EqualFold(string(pointer.From(dataProtectionReplication.Replication.EndpointType)), string(volumegroups.EndpointTypeDst)) { - return fmt.Errorf("snapshot policy cannot be enabled on a data protection volume, %s", volumeId) } @@ -539,7 +533,6 @@ func (r NetAppVolumeGroupSapHanaResource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.VolumeGroupClient id, err := volumegroups.ParseVolumeGroupID(metadata.ResourceData.Id()) @@ -591,7 +584,6 @@ func (r NetAppVolumeGroupSapHanaResource) Delete() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 120 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.VolumeGroupClient id, err := volumegroups.ParseVolumeGroupID(metadata.ResourceData.Id()) diff --git a/internal/services/netapp/netapp_volume_helper.go b/internal/services/netapp/netapp_volume_helper.go index ed6d7aab92aa..dffa0223f7e2 100644 --- a/internal/services/netapp/netapp_volume_helper.go +++ b/internal/services/netapp/netapp_volume_helper.go @@ -23,7 +23,6 @@ import ( ) func expandNetAppVolumeGroupVolumeExportPolicyRule(input []netAppModels.ExportPolicyRule) *volumegroups.VolumePropertiesExportPolicy { - if len(input) == 0 { return &volumegroups.VolumePropertiesExportPolicy{} } @@ -31,7 +30,6 @@ func expandNetAppVolumeGroupVolumeExportPolicyRule(input []netAppModels.ExportPo results := make([]volumegroups.ExportPolicyRule, 0) for _, item := range input { - // Hard-Coded values, for AVG these cannot be set differently // they are not exposed as TF configuration // but PUT request requires those fields to succeed diff --git a/internal/services/netapp/netapp_volume_quota_rule_data_source.go b/internal/services/netapp/netapp_volume_quota_rule_data_source.go index 6c55036c20ca..84fbc1474dd8 100644 --- a/internal/services/netapp/netapp_volume_quota_rule_data_source.go +++ b/internal/services/netapp/netapp_volume_quota_rule_data_source.go @@ -76,7 +76,6 @@ func (r NetAppVolumeQuotaRuleDataSource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.VolumeQuotaRules var state netAppModels.NetAppVolumeQuotaRuleDataSourceModel diff --git a/internal/services/netapp/netapp_volume_quota_rule_resource.go b/internal/services/netapp/netapp_volume_quota_rule_resource.go index 38fe1da9ed12..7d798571aa7e 100644 --- a/internal/services/netapp/netapp_volume_quota_rule_resource.go +++ b/internal/services/netapp/netapp_volume_quota_rule_resource.go @@ -180,7 +180,6 @@ func (r NetAppVolumeQuotaRuleResource) Read() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 5 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.VolumeQuotaRules id, err := volumequotarules.ParseVolumeQuotaRuleID(metadata.ResourceData.Id()) @@ -224,7 +223,6 @@ func (r NetAppVolumeQuotaRuleResource) Delete() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 120 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.NetApp.VolumeQuotaRules id, err := volumequotarules.ParseVolumeQuotaRuleID(metadata.ResourceData.Id()) diff --git a/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go b/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go index f76118b66c7e..20ea71559376 100644 --- a/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go +++ b/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go @@ -73,7 +73,6 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr // Validating each volume for _, volume := range pointer.From(volumeList) { - // Get protocol list protocolTypeList := pointer.From(volume.Properties.ProtocolTypes) protocolType := "" @@ -110,7 +109,6 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr (strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaData)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaShared)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaLog))) { - errors = append(errors, fmt.Errorf("'nfsv3 on data, log and shared volumes for %v is not supported on volume %v'", applicationType, pointer.From(volume.Name))) } @@ -126,7 +124,6 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr volume.Properties.DataProtection != nil && volume.Properties.DataProtection.Replication != nil && strings.EqualFold(string(pointer.From(volume.Properties.DataProtection.Replication.EndpointType)), string(volumegroups.EndpointTypeDst)) { - errors = append(errors, fmt.Errorf("'log volume spec type cannot be DataProtection type for %v on volume %v'", applicationType, pointer.From(volume.Name))) } @@ -134,7 +131,6 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr if volume.Properties.DataProtection != nil && volume.Properties.DataProtection.Snapshot != nil && (volume.Properties.DataProtection.Replication != nil && strings.EqualFold(string(pointer.From(volume.Properties.DataProtection.Replication.EndpointType)), string(volumegroups.EndpointTypeDst))) { - errors = append(errors, fmt.Errorf("'snapshot policy cannot be enabled on a data protection volume for %v on volume %v'", applicationType, pointer.From(volume.Name))) } @@ -142,7 +138,6 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr if (strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaDataBackup)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaLogBackup))) && pointer.From(volume.Properties.ProximityPlacementGroup) != "" { - errors = append(errors, fmt.Errorf("'%v volume spec type cannot have PPG defined for %v on volume %v'", pointer.From(volume.Properties.VolumeSpecName), applicationType, pointer.From(volume.Name))) } @@ -151,7 +146,6 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaLog)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaShared))) && pointer.From(volume.Properties.ProximityPlacementGroup) == "" { - errors = append(errors, fmt.Errorf("'%v volume spec type must have PPG defined for %v on volume %v'", pointer.From(volume.Properties.VolumeSpecName), applicationType, pointer.From(volume.Name))) } diff --git a/internal/services/netapp/validate/volume_quota_rule_quota_validations.go b/internal/services/netapp/validate/volume_quota_rule_quota_validations.go index c53e7b421298..61b39b0606e3 100644 --- a/internal/services/netapp/validate/volume_quota_rule_quota_validations.go +++ b/internal/services/netapp/validate/volume_quota_rule_quota_validations.go @@ -35,7 +35,6 @@ func ValidateNetAppVolumeQuotaRule(ctx context.Context, volumeID volumes.VolumeI // NFS Volume must not have Windows SIDs if len(pointer.From(volume.Model.Properties.ProtocolTypes)) == 1 && (findStringInSlice(pointer.From(volume.Model.Properties.ProtocolTypes), "nfsv3") || findStringInSlice(pointer.From(volume.Model.Properties.ProtocolTypes), "nfsv4.1")) { - if pointer.To(rule.QuotaTarget) != nil && rule.QuotaTarget != "" { _, errList := ValidateWindowsSID(&rule.QuotaTarget, rule.QuotaTarget) if len(errList) == 0 { @@ -46,7 +45,6 @@ func ValidateNetAppVolumeQuotaRule(ctx context.Context, volumeID volumes.VolumeI // CIFS Volume must not have Windows SIDs if len(pointer.From(volume.Model.Properties.ProtocolTypes)) == 1 && findStringInSlice(pointer.From(volume.Model.Properties.ProtocolTypes), "cifs") { - if pointer.To(rule.QuotaTarget) != nil && rule.QuotaTarget != "" { _, errList := ValidateUnixUserIDOrGroupID(&rule.QuotaTarget, rule.QuotaTarget) if len(errList) == 0 { diff --git a/internal/services/network/custom_ip_prefix_resource.go b/internal/services/network/custom_ip_prefix_resource.go index efc486d336bd..54a7fdf14e6e 100644 --- a/internal/services/network/custom_ip_prefix_resource.go +++ b/internal/services/network/custom_ip_prefix_resource.go @@ -521,7 +521,6 @@ func (r CustomIpPrefixResource) updateCommissionedState(ctx context.Context, id for startingState, path := range plan { // Look for a plan that works from our lastKnownState if *lastKnownState == startingState || transitioningStatesFor(startingState).contains(*lastKnownState) { - // If we're currently transitioning to the startingState for this plan, wait for this to complete before proceeding if lastKnownState, err = r.waitForCommissionedState(ctx, id, transitioningStatesFor(startingState), commissionedStates{startingState}); err != nil { return lastKnownState, err diff --git a/internal/services/network/express_route_circuit_authorization_resource.go b/internal/services/network/express_route_circuit_authorization_resource.go index 2effd7d2a039..7c302fe02535 100644 --- a/internal/services/network/express_route_circuit_authorization_resource.go +++ b/internal/services/network/express_route_circuit_authorization_resource.go @@ -127,7 +127,6 @@ func resourceExpressRouteCircuitAuthorizationRead(d *pluginsdk.ResourceData, met if props := model.Properties; props != nil { d.Set("authorization_key", props.AuthorizationKey) d.Set("authorization_use_status", string(pointer.From(props.AuthorizationUseStatus))) - } } diff --git a/internal/services/network/express_route_circuit_connection_resource.go b/internal/services/network/express_route_circuit_connection_resource.go index 8fc0197708dd..e287ab16c280 100644 --- a/internal/services/network/express_route_circuit_connection_resource.go +++ b/internal/services/network/express_route_circuit_connection_resource.go @@ -182,7 +182,6 @@ func resourceExpressRouteCircuitConnectionRead(d *pluginsdk.ResourceData, meta i if model := resp.Model; model != nil { if props := model.Properties; props != nil { - d.Set("address_prefix_ipv4", props.AddressPrefix) // The ExpressRoute Circuit Connection API returns "*****************" for AuthorizationKey when it's changed from a valid value to `nil` diff --git a/internal/services/network/express_route_circuit_peering_resource.go b/internal/services/network/express_route_circuit_peering_resource.go index b170cd6f9254..a9ba8b4501e3 100644 --- a/internal/services/network/express_route_circuit_peering_resource.go +++ b/internal/services/network/express_route_circuit_peering_resource.go @@ -412,7 +412,6 @@ func resourceExpressRouteCircuitPeeringUpdate(d *pluginsdk.ResourceData, meta in } if d.HasChange("ipv4_enabled") { - ipv4Enabled := d.Get("ipv4_enabled").(bool) if ipv4Enabled { payload.Properties.State = pointer.To(expressroutecircuitpeerings.ExpressRoutePeeringStateEnabled) diff --git a/internal/services/network/express_route_circuit_resource.go b/internal/services/network/express_route_circuit_resource.go index a4f88ce93763..f2482766f2b2 100644 --- a/internal/services/network/express_route_circuit_resource.go +++ b/internal/services/network/express_route_circuit_resource.go @@ -267,7 +267,6 @@ func resourceExpressRouteCircuitUpdate(d *pluginsdk.ResourceData, meta interface existing, err := client.Get(ctx, *id) if err != nil { return fmt.Errorf("retrieving %s : %s", id, err) - } if err := client.CreateOrUpdateThenPoll(ctx, *id, *existing.Model); err != nil { diff --git a/internal/services/network/express_route_gateway_resource.go b/internal/services/network/express_route_gateway_resource.go index 7e5d6f16e392..643298540ac6 100644 --- a/internal/services/network/express_route_gateway_resource.go +++ b/internal/services/network/express_route_gateway_resource.go @@ -332,7 +332,6 @@ func convertConnectionsToGatewayConnections(input *[]expressrouteconnections.Exp o.Properties.RoutingConfiguration = rc } - } output = append(output, o) } diff --git a/internal/services/network/network_interface_security_group_association_resource_test.go b/internal/services/network/network_interface_security_group_association_resource_test.go index a5c43da5cc2d..d91f142b0ee2 100644 --- a/internal/services/network/network_interface_security_group_association_resource_test.go +++ b/internal/services/network/network_interface_security_group_association_resource_test.go @@ -133,7 +133,6 @@ func (NetworkInterfaceNetworkSecurityGroupAssociationResource) destroy(ctx conte if err := client.Network.NetworkInterfaces.CreateOrUpdateThenPoll(ctx2, *id.First, *read.Model); err != nil { return fmt.Errorf("removing Network Security Group Association for %s: %+v", id.First, err) - } return nil diff --git a/internal/services/network/network_manager_admin_rule_collection_resource.go b/internal/services/network/network_manager_admin_rule_collection_resource.go index 70a34981422f..59cc30af80b8 100644 --- a/internal/services/network/network_manager_admin_rule_collection_resource.go +++ b/internal/services/network/network_manager_admin_rule_collection_resource.go @@ -237,7 +237,7 @@ func (r ManagerAdminRuleCollectionResource) Delete() sdk.ResourceFunc { } func expandNetworkManagerNetworkGroupIds(inputList []string) []adminrulecollections.NetworkManagerSecurityGroupItem { - var outputList []adminrulecollections.NetworkManagerSecurityGroupItem + outputList := make([]adminrulecollections.NetworkManagerSecurityGroupItem, 0, len(inputList)) for _, v := range inputList { input := v output := adminrulecollections.NetworkManagerSecurityGroupItem{ @@ -251,7 +251,7 @@ func expandNetworkManagerNetworkGroupIds(inputList []string) []adminrulecollecti } func flattenNetworkManagerNetworkGroupIds(inputList []adminrulecollections.NetworkManagerSecurityGroupItem) []string { - var outputList []string + outputList := make([]string, 0, len(inputList)) for _, input := range inputList { outputList = append(outputList, input.NetworkGroupId) diff --git a/internal/services/network/network_manager_admin_rule_resource.go b/internal/services/network/network_manager_admin_rule_resource.go index 7da70f43825d..15f3653aa078 100644 --- a/internal/services/network/network_manager_admin_rule_resource.go +++ b/internal/services/network/network_manager_admin_rule_resource.go @@ -405,7 +405,7 @@ func (r ManagerAdminRuleResource) Delete() sdk.ResourceFunc { } func expandAddressPrefixItemModel(inputList []AddressPrefixItemModel) *[]adminrules.AddressPrefixItem { - var outputList []adminrules.AddressPrefixItem + outputList := make([]adminrules.AddressPrefixItem, 0, len(inputList)) for _, v := range inputList { input := v output := adminrules.AddressPrefixItem{ @@ -423,11 +423,11 @@ func expandAddressPrefixItemModel(inputList []AddressPrefixItemModel) *[]adminru } func flattenAddressPrefixItemModel(inputList *[]adminrules.AddressPrefixItem) []AddressPrefixItemModel { - var outputList []AddressPrefixItemModel if inputList == nil { - return outputList + return []AddressPrefixItemModel{} } + outputList := make([]AddressPrefixItemModel, 0, len(*inputList)) for _, input := range *inputList { output := AddressPrefixItemModel{} diff --git a/internal/services/network/network_manager_connectivity_configuration_resource.go b/internal/services/network/network_manager_connectivity_configuration_resource.go index 91d003af18b7..2fb083d0fc43 100644 --- a/internal/services/network/network_manager_connectivity_configuration_resource.go +++ b/internal/services/network/network_manager_connectivity_configuration_resource.go @@ -356,7 +356,7 @@ func expandConnectivityConfIsGlobal(input bool) *connectivityconfigurations.IsGl } func expandConnectivityGroupItemModel(inputList []ConnectivityGroupItemModel) []connectivityconfigurations.ConnectivityGroupItem { - var outputList []connectivityconfigurations.ConnectivityGroupItem + outputList := make([]connectivityconfigurations.ConnectivityGroupItem, 0, len(inputList)) for _, v := range inputList { input := v output := connectivityconfigurations.ConnectivityGroupItem{ @@ -381,7 +381,7 @@ func expandUseHubGateWay(input bool) *connectivityconfigurations.UseHubGateway { } func expandHubModel(inputList []HubModel) *[]connectivityconfigurations.Hub { - var outputList []connectivityconfigurations.Hub + outputList := make([]connectivityconfigurations.Hub, 0, len(inputList)) for _, v := range inputList { input := v output := connectivityconfigurations.Hub{ @@ -410,8 +410,7 @@ func flattenConnectivityConfIsGlobal(input *connectivityconfigurations.IsGlobal) } func flattenConnectivityGroupItemModel(inputList []connectivityconfigurations.ConnectivityGroupItem) []ConnectivityGroupItemModel { - var outputList []ConnectivityGroupItemModel - + outputList := make([]ConnectivityGroupItemModel, 0, len(inputList)) for _, input := range inputList { output := ConnectivityGroupItemModel{ GroupConnectivity: input.GroupConnectivity, @@ -434,11 +433,11 @@ func flattenUseHubGateWay(input *connectivityconfigurations.UseHubGateway) bool } func flattenHubModel(inputList *[]connectivityconfigurations.Hub) []HubModel { - var outputList []HubModel if inputList == nil { - return outputList + return []HubModel{} } + outputList := make([]HubModel, 0, len(*inputList)) for _, input := range *inputList { output := HubModel{} diff --git a/internal/services/network/network_manager_resource.go b/internal/services/network/network_manager_resource.go index ce212c353f7c..9521ebd74775 100644 --- a/internal/services/network/network_manager_resource.go +++ b/internal/services/network/network_manager_resource.go @@ -357,7 +357,7 @@ func flattenNetworkManagerScope(input networkmanagers.NetworkManagerPropertiesNe } func flattenNetworkManagerScopeAccesses(input []networkmanagers.ConfigurationType) []string { - var result []string + result := make([]string, 0, len(input)) for _, v := range input { result = append(result, string(v)) } @@ -369,7 +369,7 @@ func flattenNetworkManagerCrossTenantScopes(input *[]networkmanagers.CrossTenant return make([]ManagerCrossTenantScopeModel, 0) } - var results []ManagerCrossTenantScopeModel + results := make([]ManagerCrossTenantScopeModel, 0, len(*input)) for _, v := range *input { results = append(results, ManagerCrossTenantScopeModel{ TenantId: pointer.From(v.TenantId), diff --git a/internal/services/network/network_manager_security_admin_configuration_resource.go b/internal/services/network/network_manager_security_admin_configuration_resource.go index 53b70d721ec8..d5b09ecdc2b1 100644 --- a/internal/services/network/network_manager_security_admin_configuration_resource.go +++ b/internal/services/network/network_manager_security_admin_configuration_resource.go @@ -245,7 +245,7 @@ func (r ManagerSecurityAdminConfigurationResource) Delete() sdk.ResourceFunc { } func expandNetworkIntentPolicyBasedServiceModel(inputList []string) *[]securityadminconfigurations.NetworkIntentPolicyBasedService { - var outputList []securityadminconfigurations.NetworkIntentPolicyBasedService + outputList := make([]securityadminconfigurations.NetworkIntentPolicyBasedService, 0, len(inputList)) for _, input := range inputList { output := securityadminconfigurations.NetworkIntentPolicyBasedService(input) @@ -256,11 +256,11 @@ func expandNetworkIntentPolicyBasedServiceModel(inputList []string) *[]securitya } func flattenNetworkIntentPolicyBasedServiceModel(inputList *[]securityadminconfigurations.NetworkIntentPolicyBasedService) []string { - var outputList []string if inputList == nil { - return outputList + return []string{} } + outputList := make([]string, 0, len(*inputList)) for _, input := range *inputList { outputList = append(outputList, string(input)) } diff --git a/internal/services/network/parse/application_gateway_backend_address_pool_test.go b/internal/services/network/parse/application_gateway_backend_address_pool_test.go index 063dc01044a4..9d43802f19b7 100644 --- a/internal/services/network/parse/application_gateway_backend_address_pool_test.go +++ b/internal/services/network/parse/application_gateway_backend_address_pool_test.go @@ -141,7 +141,6 @@ func TestParseApplicationGatewayBackendAddressPoolID(t *testing.T) { if actual.BackendAddressPoolName != v.Expected.BackendAddressPoolName { t.Fatalf("Expected %q but got %q for BackendAddressPoolName", v.Expected.BackendAddressPoolName, actual.BackendAddressPoolName) } - } } @@ -307,7 +306,6 @@ func TestParseApplicationGatewayBackendAddressPoolIDInsensitively(t *testing.T) if actual.BackendAddressPoolName != v.Expected.BackendAddressPoolName { t.Fatalf("Expected %q but got %q for BackendAddressPoolName", v.Expected.BackendAddressPoolName, actual.BackendAddressPoolName) } - } } diff --git a/internal/services/network/point_to_site_vpn_gateway_resource.go b/internal/services/network/point_to_site_vpn_gateway_resource.go index 98e3f79020f9..de16fa2e0d5c 100644 --- a/internal/services/network/point_to_site_vpn_gateway_resource.go +++ b/internal/services/network/point_to_site_vpn_gateway_resource.go @@ -316,7 +316,6 @@ func resourcePointToSiteVPNGatewayRead(d *pluginsdk.ResourceData, meta interface d.Set("location", location.NormalizeNilable(model.Location)) if props := model.Properties; props != nil { - d.Set("dns_servers", utils.FlattenStringSlice(props.CustomDnsServers)) flattenedConfigurations := flattenPointToSiteVPNGatewayConnectionConfiguration(props.P2SConnectionConfigurations) if err := d.Set("connection_configuration", flattenedConfigurations); err != nil { diff --git a/internal/services/network/private_endpoint_connection_data_source.go b/internal/services/network/private_endpoint_connection_data_source.go index d226f24a2d1d..90f05bfa062c 100644 --- a/internal/services/network/private_endpoint_connection_data_source.go +++ b/internal/services/network/private_endpoint_connection_data_source.go @@ -171,7 +171,6 @@ func getPrivateIpAddress(ctx context.Context, client *networkinterfaces.NetworkI } } } - } return privateIpAddress diff --git a/internal/services/network/public_ip_prefix_resource.go b/internal/services/network/public_ip_prefix_resource.go index 20cfc0f7a18d..22d393eb7200 100644 --- a/internal/services/network/public_ip_prefix_resource.go +++ b/internal/services/network/public_ip_prefix_resource.go @@ -155,7 +155,6 @@ func resourcePublicIpPrefixUpdate(d *pluginsdk.ResourceData, meta interface{}) e defer cancel() if d.HasChange("tags") { - id, err := publicipprefixes.ParsePublicIPPrefixID(d.Id()) if err != nil { return err diff --git a/internal/services/network/route_map_resource.go b/internal/services/network/route_map_resource.go index 1cfe272dede8..a758af4e7cca 100644 --- a/internal/services/network/route_map_resource.go +++ b/internal/services/network/route_map_resource.go @@ -375,11 +375,11 @@ func (r RouteMapResource) CustomizeDiff() sdk.ResourceFunc { } func expandRules(input []Rule) *[]virtualwans.RouteMapRule { - var rules []virtualwans.RouteMapRule if input == nil { return nil } + rules := make([]virtualwans.RouteMapRule, 0, len(input)) for _, v := range input { rule := virtualwans.RouteMapRule{ Name: pointer.To(v.Name), @@ -398,11 +398,11 @@ func expandRules(input []Rule) *[]virtualwans.RouteMapRule { } func expandActions(input []Action) *[]virtualwans.Action { - var actions []virtualwans.Action if input == nil { return nil } + actions := make([]virtualwans.Action, 0, len(input)) for _, v := range input { action := virtualwans.Action{ Type: pointer.To(v.Type), @@ -416,11 +416,11 @@ func expandActions(input []Action) *[]virtualwans.Action { } func expandParameters(input []Parameter) *[]virtualwans.Parameter { - var parameters []virtualwans.Parameter if input == nil { return nil } + parameters := make([]virtualwans.Parameter, 0, len(input)) for _, item := range input { v := item parameter := virtualwans.Parameter{} @@ -444,11 +444,11 @@ func expandParameters(input []Parameter) *[]virtualwans.Parameter { } func expandCriteria(input []Criterion) *[]virtualwans.Criterion { - var criteria []virtualwans.Criterion if input == nil { return nil } + criteria := make([]virtualwans.Criterion, 0, len(input)) for _, item := range input { v := item criterion := virtualwans.Criterion{ @@ -474,11 +474,11 @@ func expandCriteria(input []Criterion) *[]virtualwans.Criterion { } func flattenRules(input *[]virtualwans.RouteMapRule) []Rule { - var rules []Rule if input == nil { - return rules + return []Rule{} } + rules := make([]Rule, 0, len(*input)) for _, v := range *input { rule := Rule{ Actions: flattenActions(v.Actions), @@ -500,11 +500,11 @@ func flattenRules(input *[]virtualwans.RouteMapRule) []Rule { } func flattenActions(input *[]virtualwans.Action) []Action { - var actions []Action if input == nil { - return actions + return []Action{} } + actions := make([]Action, 0, len(*input)) for _, v := range *input { action := Action{ Parameters: flattenParameters(v.Parameters), @@ -521,11 +521,11 @@ func flattenActions(input *[]virtualwans.Action) []Action { } func flattenParameters(input *[]virtualwans.Parameter) []Parameter { - var parameters []Parameter if input == nil { - return parameters + return []Parameter{} } + parameters := make([]Parameter, 0, len(*input)) for _, v := range *input { parameter := Parameter{} @@ -548,11 +548,11 @@ func flattenParameters(input *[]virtualwans.Parameter) []Parameter { } func flattenCriteria(input *[]virtualwans.Criterion) []Criterion { - var criteria []Criterion if input == nil { - return criteria + return []Criterion{} } + criteria := make([]Criterion, 0, len(*input)) for _, v := range *input { criterion := Criterion{} diff --git a/internal/services/network/route_server_resource.go b/internal/services/network/route_server_resource.go index bac8b724ef7c..51218c026af5 100644 --- a/internal/services/network/route_server_resource.go +++ b/internal/services/network/route_server_resource.go @@ -194,7 +194,6 @@ func resourceRouteServerUpdate(d *pluginsdk.ResourceData, meta interface{}) erro existing, err := client.VirtualHubsGet(ctx, *id) if err != nil { return fmt.Errorf("retrieving %s: %+v", *id, err) - } payload := existing.Model diff --git a/internal/services/network/subnet_resource.go b/internal/services/network/subnet_resource.go index 2dd98d9f9d91..ac69b92405a5 100644 --- a/internal/services/network/subnet_resource.go +++ b/internal/services/network/subnet_resource.go @@ -871,7 +871,7 @@ func flattenSubnetServiceEndpointPolicies(input *[]subnets.ServiceEndpointPolicy return nil } - var output []interface{} + output := make([]interface{}, 0, len(*input)) for _, policy := range *input { id := "" if policy.Id != nil { diff --git a/internal/services/network/virtual_hub_resource.go b/internal/services/network/virtual_hub_resource.go index 4dbf603540cf..92f92027d888 100644 --- a/internal/services/network/virtual_hub_resource.go +++ b/internal/services/network/virtual_hub_resource.go @@ -335,7 +335,6 @@ func resourceVirtualHubRead(d *pluginsdk.ResourceData, meta interface{}) error { if model := resp.Model; model != nil { d.Set("location", location.NormalizeNilable(model.Location)) if props := model.Properties; props != nil { - d.Set("address_prefix", props.AddressPrefix) d.Set("sku", props.Sku) diff --git a/internal/services/network/virtual_hub_route_table_route_resource.go b/internal/services/network/virtual_hub_route_table_route_resource.go index d372e19341f6..af302cb3fd80 100644 --- a/internal/services/network/virtual_hub_route_table_route_resource.go +++ b/internal/services/network/virtual_hub_route_table_route_resource.go @@ -315,7 +315,6 @@ func resourceVirtualHubRouteTableRouteDelete(d *pluginsdk.ResourceData, meta int } } props.Routes = &newRoutes - } routeTable.Model.Properties = props diff --git a/internal/services/network/virtual_hub_routing_intent_resource.go b/internal/services/network/virtual_hub_routing_intent_resource.go index bf923c894725..c910485f17dd 100644 --- a/internal/services/network/virtual_hub_routing_intent_resource.go +++ b/internal/services/network/virtual_hub_routing_intent_resource.go @@ -254,11 +254,11 @@ func expandRoutingPolicy(input []RoutingPolicy) *[]virtualwans.RoutingPolicy { } func flattenRoutingPolicy(input *[]virtualwans.RoutingPolicy) []RoutingPolicy { - var result []RoutingPolicy if input == nil { - return result + return []RoutingPolicy{} } + result := make([]RoutingPolicy, 0, len(*input)) for _, v := range *input { routingPolicy := RoutingPolicy{ Destinations: v.Destinations, diff --git a/internal/services/network/virtual_network_data_source.go b/internal/services/network/virtual_network_data_source.go index 4f766e7bf0c5..08c0c09bbcf9 100644 --- a/internal/services/network/virtual_network_data_source.go +++ b/internal/services/network/virtual_network_data_source.go @@ -135,7 +135,6 @@ func dataSourceVnetRead(d *pluginsdk.ResourceData, meta interface{}) error { if err := d.Set("vnet_peerings_addresses", flattenVnetPeeringsdAddressList(props.VirtualNetworkPeerings)); err != nil { return fmt.Errorf("setting `vnet_peerings_addresses`: %v", err) } - } return tags.FlattenAndSet(d, model.Tags) } @@ -171,7 +170,6 @@ func flattenVnetPeerings(input *[]virtualnetworks.VirtualNetworkPeering) map[str continue } value = *props.RemoteVirtualNetwork.Id - } key := *vnetPeering.Name output[key] = value diff --git a/internal/services/network/virtual_network_gateway_resource.go b/internal/services/network/virtual_network_gateway_resource.go index 994e2d08e868..888eb2f5b9f4 100644 --- a/internal/services/network/virtual_network_gateway_resource.go +++ b/internal/services/network/virtual_network_gateway_resource.go @@ -1091,12 +1091,9 @@ func expandVirtualNetworkGatewayVpnClientConfig(d *pluginsdk.ResourceData, vnetG addresses = append(addresses, addr.(string)) } - confAadTenant := conf["aad_tenant"].(string) - confAadAudience := conf["aad_audience"].(string) - confAadIssuer := conf["aad_issuer"].(string) - - var rootCerts []virtualnetworkgateways.VpnClientRootCertificate - for _, rootCertSet := range conf["root_certificate"].(*pluginsdk.Set).List() { + rootCertsConf := conf["root_certificate"].([]interface{}) + rootCerts := make([]virtualnetworkgateways.VpnClientRootCertificate, 0, len(rootCertsConf)) + for _, rootCertSet := range rootCertsConf { rootCert := rootCertSet.(map[string]interface{}) r := virtualnetworkgateways.VpnClientRootCertificate{ Name: pointer.To(rootCert["name"].(string)), @@ -1107,8 +1104,9 @@ func expandVirtualNetworkGatewayVpnClientConfig(d *pluginsdk.ResourceData, vnetG rootCerts = append(rootCerts, r) } - var revokedCerts []virtualnetworkgateways.VpnClientRevokedCertificate - for _, revokedCertSet := range conf["revoked_certificate"].(*pluginsdk.Set).List() { + revokedCertsConf := conf["revoked_certificate"].([]interface{}) + revokedCerts := make([]virtualnetworkgateways.VpnClientRevokedCertificate, 0, len(revokedCertsConf)) + for _, revokedCertSet := range revokedCertsConf { revokedCert := revokedCertSet.(map[string]interface{}) r := virtualnetworkgateways.VpnClientRevokedCertificate{ Name: pointer.To(revokedCert["name"].(string)), @@ -1119,17 +1117,16 @@ func expandVirtualNetworkGatewayVpnClientConfig(d *pluginsdk.ResourceData, vnetG revokedCerts = append(revokedCerts, r) } - var vpnClientProtocols []virtualnetworkgateways.VpnClientProtocol - for _, vpnClientProtocol := range conf["vpn_client_protocols"].(*pluginsdk.Set).List() { + vpnClientProtocolsConf := conf["vpn_client_protocols"].(*pluginsdk.Set).List() + vpnClientProtocols := make([]virtualnetworkgateways.VpnClientProtocol, 0, len(vpnClientProtocolsConf)) + for _, vpnClientProtocol := range vpnClientProtocolsConf { p := virtualnetworkgateways.VpnClientProtocol(vpnClientProtocol.(string)) vpnClientProtocols = append(vpnClientProtocols, p) } - confRadiusServerAddress := conf["radius_server_address"].(string) - confRadiusServerSecret := conf["radius_server_secret"].(string) - - var vpnAuthTypes []virtualnetworkgateways.VpnAuthenticationType - for _, vpnAuthType := range conf["vpn_auth_types"].(*pluginsdk.Set).List() { + vpnAuthTypesConf := conf["vpn_auth_types"].(*pluginsdk.Set).List() + vpnAuthTypes := make([]virtualnetworkgateways.VpnAuthenticationType, 0, len(vpnAuthTypesConf)) + for _, vpnAuthType := range vpnAuthTypesConf { a := virtualnetworkgateways.VpnAuthenticationType(vpnAuthType.(string)) vpnAuthTypes = append(vpnAuthTypes, a) } @@ -1138,17 +1135,17 @@ func expandVirtualNetworkGatewayVpnClientConfig(d *pluginsdk.ResourceData, vnetG VpnClientAddressPool: &virtualnetworkgateways.AddressSpace{ AddressPrefixes: &addresses, }, - AadTenant: &confAadTenant, - AadAudience: &confAadAudience, - AadIssuer: &confAadIssuer, + AadTenant: pointer.To(conf["aad_tenant"].(string)), + AadAudience: pointer.To(conf["aad_audience"].(string)), + AadIssuer: pointer.To(conf["aad_issuer"].(string)), VngClientConnectionConfigurations: expandVirtualNetworkGatewayClientConnections(conf["virtual_network_gateway_client_connection"].([]interface{}), vnetGatewayId), VpnClientIPsecPolicies: expandVirtualNetworkGatewayIpsecPolicies(conf["ipsec_policy"].([]interface{})), VpnClientRootCertificates: &rootCerts, VpnClientRevokedCertificates: &revokedCerts, VpnClientProtocols: &vpnClientProtocols, RadiusServers: expandVirtualNetworkGatewayRadiusServers(conf["radius_server"].([]interface{})), - RadiusServerAddress: &confRadiusServerAddress, - RadiusServerSecret: &confRadiusServerSecret, + RadiusServerAddress: pointer.To(conf["radius_server_address"].(string)), + RadiusServerSecret: pointer.To(conf["radius_server_secret"].(string)), VpnAuthenticationTypes: &vpnAuthTypes, } } diff --git a/internal/services/network/vpn_gateway_resource.go b/internal/services/network/vpn_gateway_resource.go index d2275eceb877..5ad838e311e5 100644 --- a/internal/services/network/vpn_gateway_resource.go +++ b/internal/services/network/vpn_gateway_resource.go @@ -267,7 +267,6 @@ func resourceVPNGatewayCreate(d *pluginsdk.ResourceData, meta interface{}) error props := resp.Model.Properties if props.BgpSettings != nil && props.BgpSettings.BgpPeeringAddresses != nil { - val := bgpSettingsRaw[0].(map[string]interface{}) input0 := val["instance_0_bgp_peering_address"].([]interface{}) input1 := val["instance_1_bgp_peering_address"].([]interface{}) diff --git a/internal/services/network/web_application_firewall_policy_resource.go b/internal/services/network/web_application_firewall_policy_resource.go index 3c9943f62586..84edbc0569aa 100644 --- a/internal/services/network/web_application_firewall_policy_resource.go +++ b/internal/services/network/web_application_firewall_policy_resource.go @@ -778,7 +778,8 @@ func expanedWebApplicationPolicyScrubbingRules(input []interface{}) *[]webapplic if len(input) == 0 { return nil } - var res []webapplicationfirewallpolicies.WebApplicationFirewallScrubbingRules + + res := make([]webapplicationfirewallpolicies.WebApplicationFirewallScrubbingRules, 0) for _, rule := range input { v := rule.(map[string]interface{}) var item webapplicationfirewallpolicies.WebApplicationFirewallScrubbingRules @@ -1133,7 +1134,6 @@ func flattenWebApplicationFirewallPolicyLogScrubbingRules(rules *[]webapplicatio result = append(result, item) } return &result - } func flattenWebApplicationFirewallPolicyManagedRulesDefinition(input webapplicationfirewallpolicies.ManagedRulesDefinition) []interface{} { diff --git a/internal/services/networkfunction/network_function_collector_policy_resource.go b/internal/services/networkfunction/network_function_collector_policy_resource.go index a7ddd515fb4d..dd166a45a51e 100644 --- a/internal/services/networkfunction/network_function_collector_policy_resource.go +++ b/internal/services/networkfunction/network_function_collector_policy_resource.go @@ -246,7 +246,6 @@ func (r NetworkFunctionCollectorPolicyResource) Read() sdk.ResourceFunc { if properties.IngestionPolicy != nil { state.IpfxIngestion = flattenIngestionSourcesPropertiesFormatModelArray(properties.IngestionPolicy.IngestionSources) } - } state.Tags = tags.Flatten(model.Tags) @@ -313,7 +312,7 @@ func collectorPolicyDeletedRefreshFunc(ctx context.Context, client *collectorpol } func expandEmissionPoliciesPropertiesFormatModelArray(inputList []IpfxEmissionModel) *[]collectorpolicies.EmissionPoliciesPropertiesFormat { - var outputList []collectorpolicies.EmissionPoliciesPropertiesFormat + outputList := make([]collectorpolicies.EmissionPoliciesPropertiesFormat, 0, len(inputList)) for _, v := range inputList { input := v output := collectorpolicies.EmissionPoliciesPropertiesFormat{ @@ -328,7 +327,7 @@ func expandEmissionPoliciesPropertiesFormatModelArray(inputList []IpfxEmissionMo } func expandEmissionPolicyDestinationModelArray(inputList []string) *[]collectorpolicies.EmissionPolicyDestination { - var outputList []collectorpolicies.EmissionPolicyDestination + outputList := make([]collectorpolicies.EmissionPolicyDestination, 0, len(inputList)) for _, v := range inputList { output := collectorpolicies.EmissionPolicyDestination{ DestinationType: pointer.To(collectorpolicies.DestinationType(v)), @@ -345,7 +344,7 @@ func expandIngestionSourcesPropertiesFormatModelArray(inputList []IpfxIngestionM return nil } - var outputList []collectorpolicies.IngestionSourcesPropertiesFormat + outputList := make([]collectorpolicies.IngestionSourcesPropertiesFormat, 0, len(inputList)) for _, v := range inputList[0].SourceResourceIds { output := collectorpolicies.IngestionSourcesPropertiesFormat{ SourceType: pointer.To(collectorpolicies.SourceTypeResource), diff --git a/internal/services/newrelic/new_relic_tag_rule_resource.go b/internal/services/newrelic/new_relic_tag_rule_resource.go index 17ce9961fae5..c06eb580861f 100644 --- a/internal/services/newrelic/new_relic_tag_rule_resource.go +++ b/internal/services/newrelic/new_relic_tag_rule_resource.go @@ -393,7 +393,7 @@ func (r NewRelicTagRuleResource) getEmail(ctx context.Context, monitorClient *mo } func expandFilteringTagModelArray(inputList []FilteringTagModel) *[]tagrules.FilteringTag { - var outputList []tagrules.FilteringTag + outputList := make([]tagrules.FilteringTag, 0, len(inputList)) for _, v := range inputList { input := v output := tagrules.FilteringTag{ diff --git a/internal/services/nginx/nginx_certificate_resource.go b/internal/services/nginx/nginx_certificate_resource.go index dc1a1114ce7b..6a9f9ae57105 100644 --- a/internal/services/nginx/nginx_certificate_resource.go +++ b/internal/services/nginx/nginx_certificate_resource.go @@ -103,9 +103,9 @@ func (m CertificateResource) Create() sdk.ResourceFunc { req := nginxcertificate.NginxCertificate{ Properties: &nginxcertificate.NginxCertificateProperties{ - CertificateVirtualPath: pointer.FromString(model.CertificateVirtualPath), - KeyVaultSecretId: pointer.FromString(model.KeyVaultSecretId), - KeyVirtualPath: pointer.FromString(model.KeyVirtualPath), + CertificateVirtualPath: pointer.To(model.CertificateVirtualPath), + KeyVaultSecretId: pointer.To(model.KeyVaultSecretId), + KeyVirtualPath: pointer.To(model.KeyVirtualPath), }, } @@ -124,7 +124,6 @@ func (m CertificateResource) Update() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 30 * time.Minute, Func: func(ctx context.Context, meta sdk.ResourceMetaData) error { - client := meta.Client.Nginx.NginxCertificate id, err := nginxcertificate.ParseCertificateID(meta.ResourceData.Id()) if err != nil { @@ -148,7 +147,7 @@ func (m CertificateResource) Update() sdk.ResourceFunc { // have to pass all existing properties to update upd := existing.Model if meta.ResourceData.HasChange("key_virtual_path") { - upd.Properties.KeyVirtualPath = pointer.FromString(model.KeyVirtualPath) + upd.Properties.KeyVirtualPath = pointer.To(model.KeyVirtualPath) } if meta.ResourceData.HasChange("certificate_virtual_path") { diff --git a/internal/services/nginx/nginx_configuration_resource.go b/internal/services/nginx/nginx_configuration_resource.go index 2b3a4cf164a0..d7e5aafd34ea 100644 --- a/internal/services/nginx/nginx_configuration_resource.go +++ b/internal/services/nginx/nginx_configuration_resource.go @@ -26,8 +26,8 @@ type ConfigFile struct { func (c ConfigFile) toSDKModel() nginxconfiguration.NginxConfigurationFile { return nginxconfiguration.NginxConfigurationFile{ - Content: pointer.FromString(c.Content), - VirtualPath: pointer.FromString(c.VirtualPath), + Content: pointer.To(c.Content), + VirtualPath: pointer.To(c.VirtualPath), } } @@ -38,8 +38,8 @@ type ProtectedFile struct { func (c ProtectedFile) toSDKModel() nginxconfiguration.NginxConfigurationFile { return nginxconfiguration.NginxConfigurationFile{ - Content: pointer.FromString(c.Content), - VirtualPath: pointer.FromString(c.VirtualPath), + Content: pointer.To(c.Content), + VirtualPath: pointer.To(c.VirtualPath), } } @@ -52,7 +52,7 @@ type ConfigurationModel struct { } func (c ConfigurationModel) toSDKFiles() *[]nginxconfiguration.NginxConfigurationFile { - var files []nginxconfiguration.NginxConfigurationFile + files := make([]nginxconfiguration.NginxConfigurationFile, 0, len(c.ConfigFile)) for _, file := range c.ConfigFile { files = append(files, file.toSDKModel()) } @@ -63,7 +63,8 @@ func (c ConfigurationModel) toSDKProtectedFiles() *[]nginxconfiguration.NginxCon if len(c.ProtectedFile) == 0 { return nil } - var files []nginxconfiguration.NginxConfigurationFile + + files := make([]nginxconfiguration.NginxConfigurationFile, 0, len(c.ProtectedFile)) for _, file := range c.ProtectedFile { files = append(files, file.toSDKModel()) } @@ -73,9 +74,9 @@ func (c ConfigurationModel) toSDKProtectedFiles() *[]nginxconfiguration.NginxCon // ToSDKModel used in both Create and Update func (c ConfigurationModel) ToSDKModel() nginxconfiguration.NginxConfiguration { req := nginxconfiguration.NginxConfiguration{ - Name: pointer.FromString(defaultConfigurationName), + Name: pointer.To(defaultConfigurationName), Properties: &nginxconfiguration.NginxConfigurationProperties{ - RootFile: pointer.FromString(c.RootFile), + RootFile: pointer.To(c.RootFile), }, } @@ -84,7 +85,7 @@ func (c ConfigurationModel) ToSDKModel() nginxconfiguration.NginxConfiguration { if c.PackageData != "" { req.Properties.Package = &nginxconfiguration.NginxConfigurationPackage{ - Data: pointer.FromString(c.PackageData), + Data: pointer.To(c.PackageData), } } @@ -304,7 +305,7 @@ func (m ConfigurationResource) Update() sdk.ResourceFunc { upd := existing.Model // root file is required in update if meta.ResourceData.HasChange("root_file") { - upd.Properties.RootFile = pointer.FromString(model.RootFile) + upd.Properties.RootFile = pointer.To(model.RootFile) } if meta.ResourceData.HasChange("config_file") { @@ -316,7 +317,7 @@ func (m ConfigurationResource) Update() sdk.ResourceFunc { if meta.ResourceData.HasChange("package_data") { upd.Properties.Package = &nginxconfiguration.NginxConfigurationPackage{ - Data: pointer.FromString(model.PackageData), + Data: pointer.To(model.PackageData), } } diff --git a/internal/services/nginx/nginx_deployment_resource.go b/internal/services/nginx/nginx_deployment_resource.go index bc56ba27ac78..a9b406fdf866 100644 --- a/internal/services/nginx/nginx_deployment_resource.go +++ b/internal/services/nginx/nginx_deployment_resource.go @@ -384,8 +384,8 @@ func (m DeploymentResource) Create() sdk.ResourceFunc { } req := nginxdeployment.NginxDeployment{} - req.Name = pointer.FromString(model.Name) - req.Location = pointer.FromString(model.Location) + req.Name = pointer.To(model.Name) + req.Location = pointer.To(model.Location) req.Tags = pointer.FromMapOfStringStrings(model.Tags) if model.Sku != "" { @@ -394,13 +394,13 @@ func (m DeploymentResource) Create() sdk.ResourceFunc { } prop := &nginxdeployment.NginxDeploymentProperties{} - prop.ManagedResourceGroup = pointer.FromString(model.ManagedResourceGroup) + prop.ManagedResourceGroup = pointer.To(model.ManagedResourceGroup) if len(model.LoggingStorageAccount) > 0 { prop.Logging = &nginxdeployment.NginxLogging{ StorageAccount: &nginxdeployment.NginxStorageAccount{ - AccountName: pointer.FromString(model.LoggingStorageAccount[0].Name), - ContainerName: pointer.FromString(model.LoggingStorageAccount[0].ContainerName), + AccountName: pointer.To(model.LoggingStorageAccount[0].Name), + ContainerName: pointer.To(model.LoggingStorageAccount[0].ContainerName), }, } } @@ -415,7 +415,7 @@ func (m DeploymentResource) Create() sdk.ResourceFunc { var publicIPs []nginxdeployment.NginxPublicIPAddress for _, ip := range public[0].IpAddress { publicIPs = append(publicIPs, nginxdeployment.NginxPublicIPAddress{ - Id: pointer.FromString(ip), + Id: pointer.To(ip), }) } prop.NetworkProfile.FrontEndIPConfiguration.PublicIPAddresses = &publicIPs @@ -426,16 +426,16 @@ func (m DeploymentResource) Create() sdk.ResourceFunc { for _, ip := range private { alloc := nginxdeployment.NginxPrivateIPAllocationMethod(ip.AllocationMethod) privateIPs = append(privateIPs, nginxdeployment.NginxPrivateIPAddress{ - PrivateIPAddress: pointer.FromString(ip.IpAddress), + PrivateIPAddress: pointer.To(ip.IpAddress), PrivateIPAllocationMethod: &alloc, - SubnetId: pointer.FromString(ip.SubnetId), + SubnetId: pointer.To(ip.SubnetId), }) } prop.NetworkProfile.FrontEndIPConfiguration.PrivateIPAddresses = &privateIPs } if len(model.NetworkInterface) > 0 { - prop.NetworkProfile.NetworkInterfaceConfiguration.SubnetId = pointer.FromString(model.NetworkInterface[0].SubnetId) + prop.NetworkProfile.NetworkInterfaceConfiguration.SubnetId = pointer.To(model.NetworkInterface[0].SubnetId) } isBasicSKU := strings.HasPrefix(model.Sku, "basic") @@ -485,7 +485,7 @@ func (m DeploymentResource) Create() sdk.ResourceFunc { if model.Email != "" { prop.UserProfile = &nginxdeployment.NginxDeploymentUserProfile{ - PreferredEmail: pointer.FromString(model.Email), + PreferredEmail: pointer.To(model.Email), } } @@ -715,8 +715,8 @@ func (m DeploymentResource) Update() sdk.ResourceFunc { if meta.ResourceData.HasChange("logging_storage_account") && len(model.LoggingStorageAccount) > 0 { req.Properties.Logging = &nginxdeployment.NginxLogging{ StorageAccount: &nginxdeployment.NginxStorageAccount{ - AccountName: pointer.FromString(model.LoggingStorageAccount[0].Name), - ContainerName: pointer.FromString(model.LoggingStorageAccount[0].ContainerName), + AccountName: pointer.To(model.LoggingStorageAccount[0].Name), + ContainerName: pointer.To(model.LoggingStorageAccount[0].ContainerName), }, } } @@ -751,7 +751,7 @@ func (m DeploymentResource) Update() sdk.ResourceFunc { if meta.ResourceData.HasChange("email") { req.Properties.UserProfile = &nginxdeployment.NginxDeploymentUserProfile{ - PreferredEmail: pointer.FromString(model.Email), + PreferredEmail: pointer.To(model.Email), } } diff --git a/internal/services/oracle/autonomous_database_regular_resource.go b/internal/services/oracle/autonomous_database_regular_resource.go index 13f96d515fb3..211002696c52 100644 --- a/internal/services/oracle/autonomous_database_regular_resource.go +++ b/internal/services/oracle/autonomous_database_regular_resource.go @@ -269,7 +269,6 @@ func (r AutonomousDatabaseRegularResource) Update() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.Oracle.OracleClient.AutonomousDatabases id, err := autonomousdatabases.ParseAutonomousDatabaseID(metadata.ResourceData.Id()) if err != nil { @@ -392,7 +391,7 @@ func (AutonomousDatabaseRegularResource) IDValidationFunc() pluginsdk.SchemaVali } func expandAdbsCustomerContacts(customerContactsList []string) []autonomousdatabases.CustomerContact { - var customerContacts []autonomousdatabases.CustomerContact + customerContacts := make([]autonomousdatabases.CustomerContact, 0, len(customerContactsList)) for _, customerContact := range customerContactsList { customerContacts = append(customerContacts, autonomousdatabases.CustomerContact{ Email: customerContact, diff --git a/internal/services/oracle/cloud_vm_cluster_resource.go b/internal/services/oracle/cloud_vm_cluster_resource.go index 2579011be170..ce841101f858 100644 --- a/internal/services/oracle/cloud_vm_cluster_resource.go +++ b/internal/services/oracle/cloud_vm_cluster_resource.go @@ -403,7 +403,6 @@ func (r CloudVmClusterResource) Update() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.Oracle.OracleClient.CloudVMClusters id, err := cloudvmclusters.ParseCloudVMClusterID(metadata.ResourceData.Id()) if err != nil { diff --git a/internal/services/oracle/exadata_infrastructure_resource.go b/internal/services/oracle/exadata_infrastructure_resource.go index c756b2f50cd0..626d429607a7 100644 --- a/internal/services/oracle/exadata_infrastructure_resource.go +++ b/internal/services/oracle/exadata_infrastructure_resource.go @@ -254,7 +254,6 @@ func (r ExadataInfraResource) Update() sdk.ResourceFunc { return sdk.ResourceFunc{ Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { - client := metadata.Client.Oracle.OracleClient.CloudExadataInfrastructures id, err := cloudexadatainfrastructures.ParseCloudExadataInfrastructureID(metadata.ResourceData.Id()) if err != nil { @@ -358,7 +357,7 @@ func (ExadataInfraResource) IDValidationFunc() pluginsdk.SchemaValidateFunc { } func ExpandCustomerContacts(customerContactsList []string) []cloudexadatainfrastructures.CustomerContact { - var customerContacts []cloudexadatainfrastructures.CustomerContact + customerContacts := make([]cloudexadatainfrastructures.CustomerContact, 0, len(customerContactsList)) for _, customerContact := range customerContactsList { customerContacts = append(customerContacts, cloudexadatainfrastructures.CustomerContact{ Email: customerContact, @@ -368,7 +367,7 @@ func ExpandCustomerContacts(customerContactsList []string) []cloudexadatainfrast } func ExpandDayOfWeekTo(daysOfWeek []string) []cloudexadatainfrastructures.DayOfWeek { - var daysOfWeekConverted []cloudexadatainfrastructures.DayOfWeek + daysOfWeekConverted := make([]cloudexadatainfrastructures.DayOfWeek, 0, len(daysOfWeek)) for _, day := range daysOfWeek { daysOfWeekConverted = append(daysOfWeekConverted, cloudexadatainfrastructures.DayOfWeek{ Name: cloudexadatainfrastructures.DayOfWeekName(day), @@ -378,7 +377,7 @@ func ExpandDayOfWeekTo(daysOfWeek []string) []cloudexadatainfrastructures.DayOfW } func ExpandMonths(months []string) []cloudexadatainfrastructures.Month { - var monthsConverted []cloudexadatainfrastructures.Month + monthsConverted := make([]cloudexadatainfrastructures.Month, 0, len(months)) for _, month := range months { monthsConverted = append(monthsConverted, cloudexadatainfrastructures.Month{ Name: cloudexadatainfrastructures.MonthName(month), diff --git a/internal/services/oracle/validate/autonomous_database_regular.go b/internal/services/oracle/validate/autonomous_database_regular.go index b15a6efe4251..845578af1cb2 100644 --- a/internal/services/oracle/validate/autonomous_database_regular.go +++ b/internal/services/oracle/validate/autonomous_database_regular.go @@ -16,41 +16,35 @@ import ( func AutonomousDatabaseName(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return + return []string{}, append(errors, fmt.Errorf("expected type of %s to be string", k)) } firstChar, _ := utf8.DecodeRuneInString(v) if !unicode.IsLetter(firstChar) { - errors = append(errors, fmt.Errorf("%v must start with a letter", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must start with a letter", k)) } for _, r := range v { if !unicode.IsLetter(r) && !unicode.IsNumber(r) { - errors = append(errors, fmt.Errorf("%v must contain only letters and numbers", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must contain only letters and numbers", k)) } } if len(v) > 30 { - errors = append(errors, fmt.Errorf("%v must be 30 characers max", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must be 30 characers max", k)) } - return + return []string{}, []error{} } func AutonomousDatabasePassword(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return + return []string{}, append(errors, fmt.Errorf("expected type of %s to be string", k)) } if len(v) < 12 || len(v) > 30 { - errors = append(errors, fmt.Errorf("%v must be 12 to 30 characters", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must be 12 to 30 characters", k)) } hasUpper := false @@ -72,57 +66,46 @@ func AutonomousDatabasePassword(i interface{}, k string) (warnings []string, err } } if hasDoubleQuote { - errors = append(errors, fmt.Errorf("%v must not contain the double quote (\") character", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must not contain the double quote (\") character", k)) } if !hasUpper { - errors = append(errors, fmt.Errorf("%v must contain at least one uppercase letter", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must contain at least one uppercase letter", k)) } if !hasLower { - errors = append(errors, fmt.Errorf("%v must contain at least one lowercase letter", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must contain at least one lowercase letter", k)) } if !hasNumber { - errors = append(errors, fmt.Errorf("%v must contain at least one number", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must contain at least one number", k)) } if strings.Contains(v, "admin") { - errors = append(errors, fmt.Errorf("%v must not contain the username \"admin\"", k)) - return + return []string{}, append(errors, fmt.Errorf("%v must not contain the username \"admin\"", k)) } - return + return []string{}, []error{} } func CustomerContactEmail(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return + return []string{}, append(errors, fmt.Errorf("expected type of %s to be string", k)) } - _, err := mail.ParseAddress(v) - if err != nil { - errors = append(errors, fmt.Errorf("%v must be a valid email address", k)) - return + if _, err := mail.ParseAddress(v); err != nil { + return []string{}, append(errors, fmt.Errorf("%v must be a valid email address", k)) } - return warnings, errors + return []string{}, []error{} } func AdbsComputeModel(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return + return []string{}, append(errors, fmt.Errorf("expected type of %s to be string", k)) } if v != string(autonomousdatabases.ComputeModelECPU) && v != string(autonomousdatabases.ComputeModelOCPU) { - errors = append(errors, fmt.Errorf("%v must be %v or %v", k, - string(autonomousdatabases.ComputeModelECPU), string(autonomousdatabases.ComputeModelOCPU))) - return + return []string{}, append(errors, fmt.Errorf("%v must be %v or %v", k, string(autonomousdatabases.ComputeModelECPU), string(autonomousdatabases.ComputeModelOCPU))) } - return + return []string{}, []error{} } diff --git a/internal/services/orbital/helper.go b/internal/services/orbital/helper.go index ec9a7fc28bac..6a6e182f3edd 100644 --- a/internal/services/orbital/helper.go +++ b/internal/services/orbital/helper.go @@ -4,6 +4,7 @@ package orbital import ( + "errors" "fmt" "github.com/hashicorp/go-azure-helpers/lang/pointer" @@ -216,9 +217,10 @@ func SpacecraftLinkSchema() *pluginsdk.Schema { func expandSpacecraftLinks(input []SpacecraftLinkModel) ([]spacecraft.SpacecraftLink, error) { if len(input) == 0 { - return nil, fmt.Errorf("links should be defined") + return nil, errors.New("links should be defined") } - var spacecraftLink []spacecraft.SpacecraftLink + + spacecraftLink := make([]spacecraft.SpacecraftLink, 0, len(input)) for _, v := range input { link := spacecraft.SpacecraftLink{ BandwidthMHz: v.BandwidthMhz, @@ -238,7 +240,7 @@ func flattenSpacecraftLinks(input []spacecraft.SpacecraftLink) ([]SpacecraftLink return nil, fmt.Errorf("links are missing") } - var spacecraftLinkModel []SpacecraftLinkModel + spacecraftLinkModel := make([]SpacecraftLinkModel, 0, len(input)) for _, v := range input { linkModel := SpacecraftLinkModel{ BandwidthMhz: v.BandwidthMHz, @@ -255,10 +257,10 @@ func flattenSpacecraftLinks(input []spacecraft.SpacecraftLink) ([]SpacecraftLink func flattenContactProfileLinks(input []contactprofile.ContactProfileLink) ([]ContactProfileLinkModel, error) { if len(input) == 0 { - return nil, fmt.Errorf("links are missing") + return nil, errors.New("links are missing") } - var contactProfileLinkModel []ContactProfileLinkModel + contactProfileLinkModel := make([]ContactProfileLinkModel, 0, len(input)) for _, v := range input { linkModel := ContactProfileLinkModel{ Polarization: string(v.Polarization), @@ -278,10 +280,10 @@ func flattenContactProfileLinks(input []contactprofile.ContactProfileLink) ([]Co func flattenContactProfileChannel(input []contactprofile.ContactProfileLinkChannel) ([]ContactProfileChannelModel, error) { if len(input) == 0 { - return nil, fmt.Errorf("channels are missing") + return nil, errors.New("channels are missing") } - var contactProfileChannelModel []ContactProfileChannelModel + contactProfileChannelModel := make([]ContactProfileChannelModel, 0, len(input)) for _, v := range input { channelModel := ContactProfileChannelModel{ BandwidthMhz: v.BandwidthMHz, @@ -306,10 +308,10 @@ func flattenContactProfileChannel(input []contactprofile.ContactProfileLinkChann func expandContactProfileLinks(input []ContactProfileLinkModel) ([]contactprofile.ContactProfileLink, error) { if len(input) == 0 { - return nil, fmt.Errorf("links should be defined") + return nil, errors.New("links should be defined") } - var contactProfileLink []contactprofile.ContactProfileLink + contactProfileLink := make([]contactprofile.ContactProfileLink, 0, len(input)) for _, v := range input { link := contactprofile.ContactProfileLink{ Direction: contactprofile.Direction(v.Direction), @@ -329,10 +331,10 @@ func expandContactProfileLinks(input []ContactProfileLinkModel) ([]contactprofil func expandContactProfileChannel(input []ContactProfileChannelModel) ([]contactprofile.ContactProfileLinkChannel, error) { if len(input) == 0 { - return nil, fmt.Errorf("contact profile channel should be defined") + return nil, errors.New("contact profile channel should be defined") } - var contactProfileChannel []contactprofile.ContactProfileLinkChannel + contactProfileChannel := make([]contactprofile.ContactProfileLinkChannel, 0, len(input)) for _, v := range input { channel := contactprofile.ContactProfileLinkChannel{ BandwidthMHz: v.BandwidthMhz, @@ -355,7 +357,7 @@ func expandContactProfileChannel(input []ContactProfileChannelModel) ([]contactp func expandEndPoint(input []EndPointModel) ([]contactprofile.EndPoint, error) { if len(input) == 0 { - return nil, fmt.Errorf("end point should be defined") + return nil, errors.New("end point should be defined") } v := input[0] diff --git a/internal/services/paloalto/next_generation_firewall_vhub_panorama_resource_test.go b/internal/services/paloalto/next_generation_firewall_vhub_panorama_resource_test.go index d0dd7eb39f17..fd78d49aee06 100644 --- a/internal/services/paloalto/next_generation_firewall_vhub_panorama_resource_test.go +++ b/internal/services/paloalto/next_generation_firewall_vhub_panorama_resource_test.go @@ -56,7 +56,6 @@ func TestAccPaloAltoNextGenerationFirewallVHubPanoramaResource_complete(t *testi }, data.ImportStep(), }) - } func TestAccPaloAltoNextGenerationFirewallVHubPanoramaResource_update(t *testing.T) { @@ -90,7 +89,6 @@ func TestAccPaloAltoNextGenerationFirewallVHubPanoramaResource_update(t *testing }, data.ImportStep(), }) - } func (r NextGenerationFirewallVHubPanoramaResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { diff --git a/internal/services/paloalto/next_generation_firewall_vnet_panorama_resource_test.go b/internal/services/paloalto/next_generation_firewall_vnet_panorama_resource_test.go index d7665ccb3069..5e9829b11485 100644 --- a/internal/services/paloalto/next_generation_firewall_vnet_panorama_resource_test.go +++ b/internal/services/paloalto/next_generation_firewall_vnet_panorama_resource_test.go @@ -37,7 +37,6 @@ func TestAccNextGenerationFirewallVNetPanoramaResource_basic(t *testing.T) { }, data.ImportStep(), }) - } func TestAccNextGenerationFirewallVNetPanoramaResource_complete(t *testing.T) { @@ -57,7 +56,6 @@ func TestAccNextGenerationFirewallVNetPanoramaResource_complete(t *testing.T) { }, data.ImportStep(), }) - } func TestAccNextGenerationFirewallVNetPanoramaResource_update(t *testing.T) { @@ -91,7 +89,6 @@ func TestAccNextGenerationFirewallVNetPanoramaResource_update(t *testing.T) { }, data.ImportStep(), }) - } func (r NextGenerationFirewallVNetPanoramaResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { diff --git a/internal/services/paloalto/schema/network_profile.go b/internal/services/paloalto/schema/network_profile.go index 17eecabbe912..b614a72c24ea 100644 --- a/internal/services/paloalto/schema/network_profile.go +++ b/internal/services/paloalto/schema/network_profile.go @@ -391,7 +391,6 @@ func FlattenNetworkProfileVHub(input firewalls.NetworkProfile) (*NetworkProfileV result.TrustedRanges = trustedRanges if v := input.VwanConfiguration; v != nil { - result.VHubID = pointer.From(v.VHub.ResourceId) applianceID, err := networkvirtualappliances.ParseNetworkVirtualApplianceID(pointer.From(v.NetworkVirtualApplianceId)) if err != nil { diff --git a/internal/services/policy/assignment.go b/internal/services/policy/assignment.go index ec2319337f76..da125d95203d 100644 --- a/internal/services/policy/assignment.go +++ b/internal/services/policy/assignment.go @@ -43,7 +43,6 @@ func waitForPolicyAssignmentToStabilize(ctx context.Context, client *assignments } return nil, "0", fmt.Errorf("polling for %s: %+v", id, err) - } return resp, strconv.Itoa(resp.HttpResponse.StatusCode), nil diff --git a/internal/services/policy/assignment_resource_base.go b/internal/services/policy/assignment_resource_base.go index f88f877b6b33..29ca059fa8b7 100644 --- a/internal/services/policy/assignment_resource_base.go +++ b/internal/services/policy/assignment_resource_base.go @@ -640,7 +640,7 @@ func (br assignmentBaseResource) flattenOverrides(overrides *[]policyassignments return nil } - var res []interface{} + res := make([]interface{}, 0, len(*overrides)) for _, o := range *overrides { item := map[string]interface{}{ "value": pointer.From(o.Value), @@ -657,7 +657,7 @@ func (br assignmentBaseResource) flattenSelectors(selectors *[]policyassignments return nil } - var res []interface{} + res := make([]interface{}, 0, len(*selectors)) for _, s := range *selectors { item := map[string]interface{}{ "in": utils.FlattenStringSlice(s.In), @@ -675,7 +675,7 @@ func (br assignmentBaseResource) flattenResourceSelectors(selectors *[]policyass return nil } - var res []interface{} + res := make([]interface{}, 0, len(*selectors)) for _, v := range *selectors { var item = map[string]interface{}{ "name": pointer.From(v.Name), diff --git a/internal/services/policy/parse/scope.go b/internal/services/policy/parse/scope.go index 5ad240d05718..b19ac45a2051 100644 --- a/internal/services/policy/parse/scope.go +++ b/internal/services/policy/parse/scope.go @@ -4,6 +4,7 @@ package parse import ( + "errors" "fmt" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" @@ -52,7 +53,7 @@ func (id ScopeAtManagementGroup) ScopeId() string { func PolicyScopeID(input string) (PolicyScopeId, error) { if input == "" { - return nil, fmt.Errorf("unable to parse Remediation Scope ID: ID is empty") + return nil, errors.New("unable to parse Remediation Scope ID: ID is empty") } if isManagementGroupId(input) { diff --git a/internal/services/policy/policy_virtual_machine_configuration_assignment_data_source.go b/internal/services/policy/policy_virtual_machine_configuration_assignment_data_source.go index a3c996cba4ba..a9edca6976fe 100644 --- a/internal/services/policy/policy_virtual_machine_configuration_assignment_data_source.go +++ b/internal/services/policy/policy_virtual_machine_configuration_assignment_data_source.go @@ -99,7 +99,6 @@ func dataSourcePolicyVirtualMachineConfigurationAssignmentRead(d *pluginsdk.Reso if model := resp.Model; model != nil { if props := model.Properties; props != nil { - d.Set("assignment_hash", pointer.From(props.AssignmentHash)) d.Set("compliance_status", string(pointer.From(props.ComplianceStatus))) d.Set("latest_report_id", pointer.From(props.LatestReportId)) diff --git a/internal/services/postgres/postgresql_flexible_server_resource.go b/internal/services/postgres/postgresql_flexible_server_resource.go index e8da8a74e4a6..7d5b7eb89cd4 100644 --- a/internal/services/postgres/postgresql_flexible_server_resource.go +++ b/internal/services/postgres/postgresql_flexible_server_resource.go @@ -751,7 +751,6 @@ func resourcePostgresqlFlexibleServerUpdate(d *pluginsdk.ResourceData, meta inte createMode := d.Get("create_mode").(string) if createMode == "" || servers.CreateMode(createMode) == servers.CreateModeDefault { - _, adminLoginSet := d.GetOk("administrator_login") _, adminPwdSet := d.GetOk("administrator_password") diff --git a/internal/services/postgres/validate/flexible_server_storage_tier.go b/internal/services/postgres/validate/flexible_server_storage_tier.go index 689d47de8e1d..12c7cc59d9d7 100644 --- a/internal/services/postgres/validate/flexible_server_storage_tier.go +++ b/internal/services/postgres/validate/flexible_server_storage_tier.go @@ -15,7 +15,6 @@ type StorageTiers struct { // Creates a map of valid StorageTiers based on the storage_mb for the PostgreSQL Flexible Server func InitializeFlexibleServerStorageTierDefaults() map[int]StorageTiers { - storageTiersMappings := map[int]StorageTiers{ 32768: {servers.AzureManagedDiskPerformanceTiersPFour, &[]string{ string(servers.AzureManagedDiskPerformanceTiersPFour), diff --git a/internal/services/privatednsresolver/private_dns_resolver_dns_forwarding_ruleset_resource.go b/internal/services/privatednsresolver/private_dns_resolver_dns_forwarding_ruleset_resource.go index a0e5640a106f..0515a9d0dccc 100644 --- a/internal/services/privatednsresolver/private_dns_resolver_dns_forwarding_ruleset_resource.go +++ b/internal/services/privatednsresolver/private_dns_resolver_dns_forwarding_ruleset_resource.go @@ -227,7 +227,7 @@ func (r PrivateDNSResolverDnsForwardingRulesetResource) Delete() sdk.ResourceFun } func expandDnsResolverOutboundEndpoints(inputList []string) *[]dnsforwardingrulesets.SubResource { - var outputList []dnsforwardingrulesets.SubResource + outputList := make([]dnsforwardingrulesets.SubResource, 0, len(inputList)) for _, v := range inputList { output := dnsforwardingrulesets.SubResource{ Id: v, @@ -239,11 +239,11 @@ func expandDnsResolverOutboundEndpoints(inputList []string) *[]dnsforwardingrule } func flattenDnsResolverOutboundEndpoints(inputList *[]dnsforwardingrulesets.SubResource) []string { - var outputList []string if inputList == nil { - return outputList + return []string{} } + outputList := make([]string, 0, len(*inputList)) for _, input := range *inputList { output := input.Id outputList = append(outputList, output) diff --git a/internal/services/privatednsresolver/private_dns_resolver_forwarding_rule_resource.go b/internal/services/privatednsresolver/private_dns_resolver_forwarding_rule_resource.go index 606467862042..13c2b050cc80 100644 --- a/internal/services/privatednsresolver/private_dns_resolver_forwarding_rule_resource.go +++ b/internal/services/privatednsresolver/private_dns_resolver_forwarding_rule_resource.go @@ -289,7 +289,7 @@ func (r PrivateDNSResolverForwardingRuleResource) Delete() sdk.ResourceFunc { } func expandTargetDnsServerModel(inputList []TargetDnsServerModel) *[]forwardingrules.TargetDnsServer { - var outputList []forwardingrules.TargetDnsServer + outputList := make([]forwardingrules.TargetDnsServer, 0, len(inputList)) for _, v := range inputList { input := v output := forwardingrules.TargetDnsServer{ @@ -304,11 +304,11 @@ func expandTargetDnsServerModel(inputList []TargetDnsServerModel) *[]forwardingr } func flattenTargetDnsServerModel(inputList *[]forwardingrules.TargetDnsServer) []TargetDnsServerModel { - var outputList []TargetDnsServerModel if inputList == nil { - return outputList + return []TargetDnsServerModel{} } + outputList := make([]TargetDnsServerModel, 0, len(*inputList)) for _, input := range *inputList { output := TargetDnsServerModel{ IPAddress: input.IPAddress, diff --git a/internal/services/privatednsresolver/private_dns_resolver_inbound_endpoint_resource.go b/internal/services/privatednsresolver/private_dns_resolver_inbound_endpoint_resource.go index c2d19f9f2b67..00d3ff523a14 100644 --- a/internal/services/privatednsresolver/private_dns_resolver_inbound_endpoint_resource.go +++ b/internal/services/privatednsresolver/private_dns_resolver_inbound_endpoint_resource.go @@ -288,7 +288,7 @@ func dnsResolverInboundEndpointDeleteRefreshFunc(ctx context.Context, client *in } func expandIPConfigurationModel(inputList []IPConfigurationModel) (*[]inboundendpoints.IPConfiguration, error) { - var outputList []inboundendpoints.IPConfiguration + outputList := make([]inboundendpoints.IPConfiguration, 0, len(inputList)) for _, v := range inputList { input := v output := inboundendpoints.IPConfiguration{} @@ -320,11 +320,11 @@ func expandIPConfigurationModel(inputList []IPConfigurationModel) (*[]inboundend } func flattenIPConfigurationModel(inputList *[]inboundendpoints.IPConfiguration) []IPConfigurationModel { - var outputList []IPConfigurationModel if inputList == nil { - return outputList + return []IPConfigurationModel{} } + outputList := make([]IPConfigurationModel, 0, len(*inputList)) for _, input := range *inputList { output := IPConfigurationModel{} diff --git a/internal/services/recoveryservices/azuresdkhacks/client.go b/internal/services/recoveryservices/azuresdkhacks/client.go index 30972f0da732..5e15a39cf453 100644 --- a/internal/services/recoveryservices/azuresdkhacks/client.go +++ b/internal/services/recoveryservices/azuresdkhacks/client.go @@ -1,8 +1,6 @@ package azuresdkhacks import ( - "fmt" - "github.com/Azure/go-autorest/autorest" ) @@ -16,7 +14,7 @@ import ( const defaultApiVersion = "2024-04-01" func userAgent() string { - return fmt.Sprintf("hashicorp/go-azure-sdk/vaultcertificates/%s", defaultApiVersion) + return "hashicorp/go-azure-sdk/vaultcertificates/" + defaultApiVersion } type VaultCertificatesClient struct { diff --git a/internal/services/recoveryservices/recovery_services_vault_resource.go b/internal/services/recoveryservices/recovery_services_vault_resource.go index 46cb32707bdc..f61ef3710be1 100644 --- a/internal/services/recoveryservices/recovery_services_vault_resource.go +++ b/internal/services/recoveryservices/recovery_services_vault_resource.go @@ -298,7 +298,6 @@ func resourceRecoveryServicesVaultCreate(d *pluginsdk.ResourceData, meta interfa if err != nil { return fmt.Errorf("updating Recovery Service %s: %+v, but recovery vault was created, a manually import might be required", id.String(), err) } - } // an update on the vault will reset the vault config to default, so we handle it at last. enhancedSecurityState := backupresourcevaultconfigs.EnhancedSecurityStateEnabled @@ -594,7 +593,6 @@ func resourceRecoveryServicesVaultRead(d *pluginsdk.ResourceData, meta interface } if prop := model.Properties; prop != nil { - immutability := vaults.ImmutabilityStateDisabled if prop.SecuritySettings != nil && prop.SecuritySettings.ImmutabilitySettings != nil { immutability = pointer.From(prop.SecuritySettings.ImmutabilitySettings.State) diff --git a/internal/services/recoveryservices/site_recovery_hyperv_replication_policy_resource.go b/internal/services/recoveryservices/site_recovery_hyperv_replication_policy_resource.go index bc66dc1bca1b..9ab0beff0016 100644 --- a/internal/services/recoveryservices/site_recovery_hyperv_replication_policy_resource.go +++ b/internal/services/recoveryservices/site_recovery_hyperv_replication_policy_resource.go @@ -161,7 +161,6 @@ func (r ReplicationPolicyHyperVResource) Read() sdk.ResourceFunc { if detail.RecoveryPointHistoryDurationInHours != nil { state.RecoveryPointRetentionInHours = *detail.RecoveryPointHistoryDurationInHours } - } } return metadata.Encode(&state) diff --git a/internal/services/recoveryservices/site_recovery_replicated_vm_resource.go b/internal/services/recoveryservices/site_recovery_replicated_vm_resource.go index d9176dc05f29..e7d903ca9981 100644 --- a/internal/services/recoveryservices/site_recovery_replicated_vm_resource.go +++ b/internal/services/recoveryservices/site_recovery_replicated_vm_resource.go @@ -465,41 +465,30 @@ func resourceSiteRecoveryReplicatedItemCreate(d *pluginsdk.ResourceData, meta in } } - var managedDisks []replicationprotecteditems.A2AVMManagedDiskInputDetails - - for _, raw := range d.Get("managed_disk").(*pluginsdk.Set).List() { + managedDisksGet := d.Get("managed_disk").(*pluginsdk.Set).List() + managedDisks := make([]replicationprotecteditems.A2AVMManagedDiskInputDetails, 0, len(managedDisksGet)) + for _, raw := range managedDisksGet { diskInput := raw.(map[string]interface{}) - diskId := diskInput["disk_id"].(string) - primaryStagingAzureStorageAccountID := diskInput["staging_storage_account_id"].(string) - recoveryResourceGroupId := diskInput["target_resource_group_id"].(string) - targetReplicaDiskType := diskInput["target_replica_disk_type"].(string) - targetDiskType := diskInput["target_disk_type"].(string) - targetEncryptionDiskSetID := diskInput["target_disk_encryption_set_id"].(string) - managedDisks = append(managedDisks, replicationprotecteditems.A2AVMManagedDiskInputDetails{ - DiskId: diskId, - PrimaryStagingAzureStorageAccountId: primaryStagingAzureStorageAccountID, - RecoveryResourceGroupId: recoveryResourceGroupId, - RecoveryReplicaDiskAccountType: &targetReplicaDiskType, - RecoveryTargetDiskAccountType: &targetDiskType, - RecoveryDiskEncryptionSetId: &targetEncryptionDiskSetID, + DiskId: diskInput["disk_id"].(string), + PrimaryStagingAzureStorageAccountId: diskInput["staging_storage_account_id"].(string), + RecoveryResourceGroupId: diskInput["target_resource_group_id"].(string), + RecoveryReplicaDiskAccountType: pointer.To(diskInput["target_replica_disk_type"].(string)), + RecoveryTargetDiskAccountType: pointer.To(diskInput["target_disk_type"].(string)), + RecoveryDiskEncryptionSetId: pointer.To(diskInput["target_disk_encryption_set_id"].(string)), DiskEncryptionInfo: expandDiskEncryption(diskInput["target_disk_encryption"].([]interface{})), }) } - var vmDisks []replicationprotecteditems.A2AVMDiskInputDetails - for _, raw := range d.Get("unmanaged_disk").(*pluginsdk.Set).List() { + vmDisksGet := d.Get("unmanaged_disk").(*pluginsdk.Set).List() + vmDisks := make([]replicationprotecteditems.A2AVMDiskInputDetails, 0, len(vmDisksGet)) + for _, raw := range vmDisksGet { diskInput := raw.(map[string]interface{}) - diskUri := diskInput["disk_uri"].(string) - primaryStagingAzureStorageAccountID := diskInput["staging_storage_account_id"].(string) - recoveryAzureStorageAccountId := diskInput["target_storage_account_id"].(string) - vmDisks = append(vmDisks, replicationprotecteditems.A2AVMDiskInputDetails{ - DiskUri: diskUri, - PrimaryStagingAzureStorageAccountId: primaryStagingAzureStorageAccountID, - RecoveryAzureStorageAccountId: recoveryAzureStorageAccountId, + DiskUri: diskInput["disk_uri"].(string), + PrimaryStagingAzureStorageAccountId: diskInput["staging_storage_account_id"].(string), + RecoveryAzureStorageAccountId: diskInput["target_storage_account_id"].(string), }) - } parameters := replicationprotecteditems.EnableProtectionInput{ @@ -511,11 +500,11 @@ func resourceSiteRecoveryReplicatedItemCreate(d *pluginsdk.ResourceData, meta in RecoveryResourceGroupId: &targetResourceGroupId, RecoveryAvailabilitySetId: targetAvailabilitySetID, RecoveryAvailabilityZone: targetAvailabilityZone, - MultiVMGroupName: utils.String(d.Get("multi_vm_group_name").(string)), - RecoveryProximityPlacementGroupId: utils.String(d.Get("target_proximity_placement_group_id").(string)), - RecoveryBootDiagStorageAccountId: utils.String(d.Get("target_boot_diagnostic_storage_account_id").(string)), - RecoveryCapacityReservationGroupId: utils.String(d.Get("target_capacity_reservation_group_id").(string)), - RecoveryVirtualMachineScaleSetId: utils.String(d.Get("target_virtual_machine_scale_set_id").(string)), + MultiVMGroupName: pointer.To(d.Get("multi_vm_group_name").(string)), + RecoveryProximityPlacementGroupId: pointer.To(d.Get("target_proximity_placement_group_id").(string)), + RecoveryBootDiagStorageAccountId: pointer.To(d.Get("target_boot_diagnostic_storage_account_id").(string)), + RecoveryCapacityReservationGroupId: pointer.To(d.Get("target_capacity_reservation_group_id").(string)), + RecoveryVirtualMachineScaleSetId: pointer.To(d.Get("target_virtual_machine_scale_set_id").(string)), VMManagedDisks: &managedDisks, VMDisks: &vmDisks, RecoveryExtendedLocation: expandEdgeZone(d.Get("target_edge_zone").(string)), @@ -569,8 +558,8 @@ func resourceSiteRecoveryReplicatedItemUpdateInternal(ctx context.Context, d *pl targetAvailabilitySetID = nil } - var vmNics []replicationprotecteditems.VMNicInputDetails nicList := d.Get("network_interface").(*pluginsdk.Set).List() + vmNics := make([]replicationprotecteditems.VMNicInputDetails, 0, len(nicList)) for _, raw := range nicList { vmNicInput := raw.(map[string]interface{}) sourceNicId := vmNicInput["source_network_interface_id"].(string) @@ -602,8 +591,9 @@ func resourceSiteRecoveryReplicatedItemUpdateInternal(ctx context.Context, d *pl }) } - var managedDisks []replicationprotecteditems.A2AVMManagedDiskUpdateDetails - for _, raw := range d.Get("managed_disk").(*pluginsdk.Set).List() { + managedDisksGet := d.Get("managed_disk").(*pluginsdk.Set).List() + managedDisks := make([]replicationprotecteditems.A2AVMManagedDiskUpdateDetails, 0, len(managedDisksGet)) + for _, raw := range managedDisksGet { diskInput := raw.(map[string]interface{}) diskId := diskInput["disk_id"].(string) targetReplicaDiskType := diskInput["target_replica_disk_type"].(string) diff --git a/internal/services/recoveryservices/site_recovery_replicated_vm_resource_test.go b/internal/services/recoveryservices/site_recovery_replicated_vm_resource_test.go index 8fde6a96ac2a..f039b0cfa89a 100644 --- a/internal/services/recoveryservices/site_recovery_replicated_vm_resource_test.go +++ b/internal/services/recoveryservices/site_recovery_replicated_vm_resource_test.go @@ -2154,7 +2154,6 @@ resource "azurerm_site_recovery_replicated_vm" "test" { ] } `, r.template(data), data.RandomInteger) - } func (r SiteRecoveryReplicatedVmResource) withAvailabilitySet(data acceptance.TestData) string { diff --git a/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go b/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go index ff5ebe6bebfc..9f8ddf1cb260 100644 --- a/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go +++ b/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go @@ -618,7 +618,6 @@ func expandRecoveryGroup(input []RecoveryGroupModel) ([]replicationrecoveryplans StartGroupActions: &preActions, EndGroupActions: &postActions, }) - } return output, nil } @@ -755,7 +754,6 @@ func validateRecoveryGroup(input []RecoveryGroupModel) (bool, error) { return false, fmt.Errorf("`fabric_location` must not be specified for `recovery_group` with `ManualActionDetails` type.") } } - } if bootCount == 0 || shutdownCount == 0 || failoverCount == 0 { diff --git a/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource_test.go b/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource_test.go index 36fbce384d31..e19ae9e0c3c1 100644 --- a/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource_test.go +++ b/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource_test.go @@ -489,7 +489,6 @@ resource "azurerm_site_recovery_replication_recovery_plan" "test" { } `, r.template(data), data.RandomInteger) - } func (r SiteRecoveryReplicationRecoveryPlan) withMultiActions(data acceptance.TestData) string { diff --git a/internal/services/recoveryservices/site_recovery_vmware_replication_policy_association_resource.go b/internal/services/recoveryservices/site_recovery_vmware_replication_policy_association_resource.go index 507ba3bf64a0..35e282b5d437 100644 --- a/internal/services/recoveryservices/site_recovery_vmware_replication_policy_association_resource.go +++ b/internal/services/recoveryservices/site_recovery_vmware_replication_policy_association_resource.go @@ -161,7 +161,6 @@ func (s VMWareReplicationPolicyAssociationResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if prop := model.Properties; prop != nil { - policyId := "" // tracked on https://github.com/Azure/azure-rest-api-specs/issues/24751 if prop.PolicyId != nil && *prop.PolicyId != "" { diff --git a/internal/services/recoveryservices/site_recovery_vmware_replication_policy_resource.go b/internal/services/recoveryservices/site_recovery_vmware_replication_policy_resource.go index 61ce499ce584..54c556dbb8e7 100644 --- a/internal/services/recoveryservices/site_recovery_vmware_replication_policy_resource.go +++ b/internal/services/recoveryservices/site_recovery_vmware_replication_policy_resource.go @@ -222,7 +222,6 @@ func (r VMWareReplicationPolicyResource) Update() sdk.ResourceFunc { return nil }, } - } func (r VMWareReplicationPolicyResource) Delete() sdk.ResourceFunc { diff --git a/internal/services/redis/redis_cache_resource_test.go b/internal/services/redis/redis_cache_resource_test.go index ab800e7765c4..1d50066d9c57 100644 --- a/internal/services/redis/redis_cache_resource_test.go +++ b/internal/services/redis/redis_cache_resource_test.go @@ -605,7 +605,6 @@ func (t RedisCacheResource) Exists(ctx context.Context, clients *clients.Client, } func (RedisCacheResource) basic(data acceptance.TestData, requireSSL bool) string { - return fmt.Sprintf(` provider "azurerm" { features {} diff --git a/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_flash_sku_support.go b/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_flash_sku_support.go index 4eac0f8ba33a..855d4447aea0 100644 --- a/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_flash_sku_support.go +++ b/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_flash_sku_support.go @@ -25,9 +25,10 @@ func RedisEnterpriseClusterLocationFlashSkuSupport(input string) error { } func invalidRedisEnterpriseClusterFlashLocations() []string { - var validFlash []string + locations := friendlyInvalidRedisEnterpriseClusterFlashLocations() + validFlash := make([]string, 0, len(locations)) - for _, v := range friendlyInvalidRedisEnterpriseClusterFlashLocations() { + for _, v := range locations { validFlash = append(validFlash, location.Normalize(v)) } diff --git a/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_zone_support.go b/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_zone_support.go index 8877f1f2c46a..9a7701cbd55b 100644 --- a/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_zone_support.go +++ b/internal/services/redisenterprise/validate/redis_enterprise_cluster_location_zone_support.go @@ -25,9 +25,10 @@ func RedisEnterpriseClusterLocationZoneSupport(input string) error { } func invalidRedisEnterpriseClusterZoneLocations() []string { - var invalidZone []string + locations := friendlyInvalidRedisEnterpriseClusterZoneLocations() + invalidZone := make([]string, 0, len(locations)) - for _, v := range friendlyInvalidRedisEnterpriseClusterZoneLocations() { + for _, v := range locations { invalidZone = append(invalidZone, location.Normalize(v)) } diff --git a/internal/services/resource/parse/resource_provider.go b/internal/services/resource/parse/resource_provider.go index 4a245988516c..a6ed50fff5b4 100644 --- a/internal/services/resource/parse/resource_provider.go +++ b/internal/services/resource/parse/resource_provider.go @@ -4,6 +4,7 @@ package parse import ( + "errors" "fmt" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" @@ -46,11 +47,11 @@ func ResourceProviderID(input string) (*ResourceProviderId, error) { } if resourceId.SubscriptionId == "" { - return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + return nil, errors.New("ID was missing the 'subscriptions' element") } if resourceId.ResourceProvider == "" { - return nil, fmt.Errorf("ID was missing the 'providers' element") + return nil, errors.New("ID was missing the 'providers' element") } if err := id.ValidateNoEmptySegments(input); err != nil { diff --git a/internal/services/resource/resource_deployment_script_common.go b/internal/services/resource/resource_deployment_script_common.go index 00d960f4ffd2..bcc255d3c914 100644 --- a/internal/services/resource/resource_deployment_script_common.go +++ b/internal/services/resource/resource_deployment_script_common.go @@ -321,7 +321,7 @@ func expandContainerConfigurationModel(inputList []ContainerConfigurationModel) } func expandEnvironmentVariableModelArray(inputList []EnvironmentVariableModel) *[]deploymentscripts.EnvironmentVariable { - var outputList []deploymentscripts.EnvironmentVariable + outputList := make([]deploymentscripts.EnvironmentVariable, 0, len(inputList)) for _, v := range inputList { input := v output := deploymentscripts.EnvironmentVariable{ @@ -378,11 +378,11 @@ func flattenContainerConfigurationModel(input *deploymentscripts.ContainerConfig } func flattenEnvironmentVariableModelArray(inputList *[]deploymentscripts.EnvironmentVariable, originalList []EnvironmentVariableModel) []EnvironmentVariableModel { - var outputList []EnvironmentVariableModel if inputList == nil { - return outputList + return []EnvironmentVariableModel{} } + outputList := make([]EnvironmentVariableModel, 0, len(*inputList)) for _, input := range *inputList { output := EnvironmentVariableModel{ Name: input.Name, diff --git a/internal/services/resource/resource_group_resource.go b/internal/services/resource/resource_group_resource.go index 472b049b7502..76c9fe583ea7 100644 --- a/internal/services/resource/resource_group_resource.go +++ b/internal/services/resource/resource_group_resource.go @@ -130,7 +130,6 @@ func resourceResourceGroupCreateUpdate(d *pluginsdk.ResourceData, meta interface } return true, "Done", nil - }, } diff --git a/internal/services/search/search_service_resource.go b/internal/services/search/search_service_resource.go index f6535699ab91..daedfa8b7850 100644 --- a/internal/services/search/search_service_resource.go +++ b/internal/services/search/search_service_resource.go @@ -4,6 +4,7 @@ package search import ( + "errors" "fmt" "log" "strings" @@ -259,7 +260,7 @@ func resourceSearchServiceCreate(d *pluginsdk.ResourceData, meta interface{}) er } if !localAuthenticationEnabled && authenticationFailureMode != "" { - return fmt.Errorf("'authentication_failure_mode' cannot be defined if 'local_authentication_enabled' has been set to 'true'") + return errors.New("'authentication_failure_mode' cannot be defined if 'local_authentication_enabled' has been set to 'true'") } // API Only Mode (Default) (e.g. localAuthenticationEnabled = true)... diff --git a/internal/services/securitycenter/security_center_server_vulnerability_assessments_setting_resource.go b/internal/services/securitycenter/security_center_server_vulnerability_assessments_setting_resource.go index c96f952a2f6c..b67b7c481b9f 100644 --- a/internal/services/securitycenter/security_center_server_vulnerability_assessments_setting_resource.go +++ b/internal/services/securitycenter/security_center_server_vulnerability_assessments_setting_resource.go @@ -20,7 +20,6 @@ import ( ) func resourceSecurityCenterServerVulnerabilityAssessmentsSetting() *pluginsdk.Resource { - return &pluginsdk.Resource{ Create: resourceSecurityCenterServerVulnerabilityAssessmentsSettingCreateOrUpdate, Read: resourceSecurityCenterServerVulnerabilityAssessmentsSettingRead, diff --git a/internal/services/securitycenter/security_center_subscription_pricing_resource.go b/internal/services/securitycenter/security_center_subscription_pricing_resource.go index 4f1581d1bb8f..ac746bcc59e6 100644 --- a/internal/services/securitycenter/security_center_subscription_pricing_resource.go +++ b/internal/services/securitycenter/security_center_subscription_pricing_resource.go @@ -262,8 +262,8 @@ func resourceSecurityCenterSubscriptionPricingDelete(d *pluginsdk.ResourceData, func expandSecurityCenterSubscriptionPricingExtensions(inputList []interface{}, extensionsStatusFromBackend *[]pricings_v2023_01_01.Extension) *[]pricings_v2023_01_01.Extension { extensionStatuses := map[string]bool{} extensionProperties := make(map[string]interface{}) - var outputList []pricings_v2023_01_01.Extension + outputList := make([]pricings_v2023_01_01.Extension, 0, len(inputList)) if extensionsStatusFromBackend != nil { for _, backendExtension := range *extensionsStatusFromBackend { // set the default value to false, then turn on the extension that appear in the template @@ -284,7 +284,6 @@ func expandSecurityCenterSubscriptionPricingExtensions(inputList []interface{}, } for extensionName, toBeEnabled := range extensionStatuses { - isEnabled := pricings_v2023_01_01.IsEnabledFalse if toBeEnabled { isEnabled = pricings_v2023_01_01.IsEnabledTrue diff --git a/internal/services/sentinel/sentinel_alert_rule.go b/internal/services/sentinel/sentinel_alert_rule.go index 2c2612e11427..0f8e28d0bca0 100644 --- a/internal/services/sentinel/sentinel_alert_rule.go +++ b/internal/services/sentinel/sentinel_alert_rule.go @@ -310,8 +310,7 @@ func expandAlertRuleAlertDynamicProperties(input []interface{}) *[]alertrules.Al return nil } - var output []alertrules.AlertPropertyMapping - + output := make([]alertrules.AlertPropertyMapping, 0, len(input)) for _, v := range input { b := v.(map[string]interface{}) property := alertrules.AlertProperty(b["name"].(string)) @@ -325,11 +324,11 @@ func expandAlertRuleAlertDynamicProperties(input []interface{}) *[]alertrules.Al } func flattenAlertRuleAlertDynamicProperties(input *[]alertrules.AlertPropertyMapping) []interface{} { - output := make([]interface{}, 0) if input == nil || len(*input) == 0 { - return output + return []interface{}{} } + output := make([]interface{}, 0, len(*input)) for _, i := range *input { name := "" if i.AlertProperty != nil { @@ -349,8 +348,7 @@ func expandAlertRuleEntityMapping(input []interface{}) *[]alertrules.EntityMappi return nil } - result := make([]alertrules.EntityMapping, 0) - + result := make([]alertrules.EntityMapping, 0, len(input)) for _, e := range input { b := e.(map[string]interface{}) mappingType := alertrules.EntityMappingType(b["entity_type"].(string)) @@ -368,8 +366,7 @@ func flattenAlertRuleEntityMapping(input *[]alertrules.EntityMapping) []interfac return []interface{}{} } - output := make([]interface{}, 0) - + output := make([]interface{}, 0, len(*input)) for _, e := range *input { entityType := "" if e.EntityType != nil { @@ -389,8 +386,7 @@ func expandAlertRuleFieldMapping(input []interface{}) *[]alertrules.FieldMapping return nil } - result := make([]alertrules.FieldMapping, 0) - + result := make([]alertrules.FieldMapping, 0, len(input)) for _, e := range input { b := e.(map[string]interface{}) result = append(result, alertrules.FieldMapping{ @@ -407,8 +403,7 @@ func flattenAlertRuleFieldMapping(input *[]alertrules.FieldMapping) []interface{ return []interface{}{} } - output := make([]interface{}, 0) - + output := make([]interface{}, 0, len(*input)) for _, e := range *input { var identifier string if e.Identifier != nil { @@ -434,8 +429,7 @@ func expandAlertRuleSentinelEntityMapping(input []interface{}) *[]alertrules.Sen return nil } - result := make([]alertrules.SentinelEntityMapping, 0) - + result := make([]alertrules.SentinelEntityMapping, 0, len(input)) for _, e := range input { b := e.(map[string]interface{}) result = append(result, alertrules.SentinelEntityMapping{ @@ -451,8 +445,7 @@ func flattenAlertRuleSentinelEntityMapping(input *[]alertrules.SentinelEntityMap return []interface{}{} } - output := make([]interface{}, 0) - + output := make([]interface{}, 0, len(*input)) for _, e := range *input { var columnName string if e.ColumnName != nil { diff --git a/internal/services/sentinel/sentinel_alert_rule_anomaly.go b/internal/services/sentinel/sentinel_alert_rule_anomaly.go index 87a523b54961..ad8d480534af 100644 --- a/internal/services/sentinel/sentinel_alert_rule_anomaly.go +++ b/internal/services/sentinel/sentinel_alert_rule_anomaly.go @@ -293,7 +293,6 @@ func AlertRuleAnomalyReadWithPredicate(ctx context.Context, baseClient securityi if predicateFunc(v) { return v, nil } - } if err := resp.NextWithContext(ctx); err != nil { return nil, fmt.Errorf("listing next: %+v", err) diff --git a/internal/services/sentinel/sentinel_log_analytics_workspace_onboard_resource_test.go b/internal/services/sentinel/sentinel_log_analytics_workspace_onboard_resource_test.go index 71c59125d14a..c5bae6f32e4e 100644 --- a/internal/services/sentinel/sentinel_log_analytics_workspace_onboard_resource_test.go +++ b/internal/services/sentinel/sentinel_log_analytics_workspace_onboard_resource_test.go @@ -49,7 +49,6 @@ func TestAccSecurityInsightsSentinelOnboardingState_basicWithName(t *testing.T) } func TestAccSecurityInsightsSentinelOnboardingState_ToggleCmkEnabled(t *testing.T) { - if os.Getenv("ARM_RUN_TEST_LOG_ANALYTICS_CLUSTERS") == "" { t.Skip("Skipping as ARM_RUN_TEST_LOG_ANALYTICS_CLUSTERS is not specified") return diff --git a/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go b/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go index aaad70081239..c3767f33cd07 100644 --- a/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go +++ b/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go @@ -589,7 +589,6 @@ func (r ThreatIntelligenceIndicator) Update() sdk.ResourceFunc { if metadata.ResourceData.HasChange("external_reference") { properties.ExternalReferences = expandThreatIntelligenceExternalReferenceModel(model.ExternalRefrence) - } if metadata.ResourceData.HasChange("granular_marking") { @@ -821,7 +820,7 @@ func (r ThreatIntelligenceIndicator) Delete() sdk.ResourceFunc { } func expandThreatIntelligenceExternalReferenceModel(inputList []externalReferenceModel) *[]securityinsight.ThreatIntelligenceExternalReference { - var outputList []securityinsight.ThreatIntelligenceExternalReference + outputList := make([]securityinsight.ThreatIntelligenceExternalReference, 0, len(inputList)) for _, v := range inputList { input := v hashesValue := make(map[string]*string, 0) @@ -886,7 +885,7 @@ func flattenThreatIntelligenceExternalReferenceModel(input *[]securityinsight.Th } func expandThreatIntelligenceGranularMarkingModelModel(inputList []granularMarkingModel) *[]azuresdkhacks.ThreatIntelligenceGranularMarkingModel { - var outputList []azuresdkhacks.ThreatIntelligenceGranularMarkingModel + outputList := make([]azuresdkhacks.ThreatIntelligenceGranularMarkingModel, 0, len(inputList)) for _, v := range inputList { input := v output := azuresdkhacks.ThreatIntelligenceGranularMarkingModel{ @@ -926,7 +925,7 @@ func flattenThreatIntelligenceGranularMarkingModelModel(input *[]azuresdkhacks.T } func expandThreatIntelligenceKillChainPhaseModel(inputList []killChainPhaseModel) *[]securityinsight.ThreatIntelligenceKillChainPhase { - var outputList []securityinsight.ThreatIntelligenceKillChainPhase + outputList := make([]securityinsight.ThreatIntelligenceKillChainPhase, 0, len(inputList)) for _, v := range inputList { input := v output := securityinsight.ThreatIntelligenceKillChainPhase{ diff --git a/internal/services/sentinel/sentinel_watchlist_resource.go b/internal/services/sentinel/sentinel_watchlist_resource.go index 82ec939180b8..18d28f8e42c4 100644 --- a/internal/services/sentinel/sentinel_watchlist_resource.go +++ b/internal/services/sentinel/sentinel_watchlist_resource.go @@ -182,7 +182,6 @@ func (r WatchlistResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if props := model.Properties; props != nil { - watchList.DisplayName = props.DisplayName watchList.ItemSearchKey = props.ItemsSearchKey watchList.Description = pointer.From(props.Description) diff --git a/internal/services/servicebus/servicebus_namespace_resource.go b/internal/services/servicebus/servicebus_namespace_resource.go index 79d85622dd88..f68d7af1c46a 100644 --- a/internal/services/servicebus/servicebus_namespace_resource.go +++ b/internal/services/servicebus/servicebus_namespace_resource.go @@ -712,7 +712,6 @@ func flattenServiceBusNamespaceNetworkRuleSet(networkRuleSet namespaces.NetworkR !trustedServiceEnabled && len(networkRules) == 0 && len(ipRules) == 0 { - return []interface{}{} } } diff --git a/internal/services/servicebus/servicebus_subscription_resource.go b/internal/services/servicebus/servicebus_subscription_resource.go index a0400c6406ea..5173497cde2e 100644 --- a/internal/services/servicebus/servicebus_subscription_resource.go +++ b/internal/services/servicebus/servicebus_subscription_resource.go @@ -176,7 +176,6 @@ func resourceServicebusSubscriptionSchema() map[string]*pluginsdk.Schema { } if !features.FourPointOhBeta() { - schema["auto_delete_on_idle"] = &pluginsdk.Schema{ Type: pluginsdk.TypeString, Optional: true, @@ -252,7 +251,6 @@ func resourceServiceBusSubscriptionCreateUpdate(d *pluginsdk.ResourceData, meta enableBatchedOperations := d.Get("batched_operations_enabled").(bool) if !features.FourPointOhBeta() { - if v := d.GetRawConfig().AsValueMap()["enable_batched_operations"]; !v.IsNull() { enableBatchedOperations = d.Get("enable_batched_operations").(bool) } diff --git a/internal/services/signalr/signalr_service_custom_domain_resource_test.go b/internal/services/signalr/signalr_service_custom_domain_resource_test.go index 9a9841da0e7f..2f38b140d621 100644 --- a/internal/services/signalr/signalr_service_custom_domain_resource_test.go +++ b/internal/services/signalr/signalr_service_custom_domain_resource_test.go @@ -60,7 +60,6 @@ func (r SignalrServiceCustomDomainResource) Exists(ctx context.Context, client * return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } return utils.Bool(resp.Model != nil), nil - } func (r SignalrServiceCustomDomainResource) basic(data acceptance.TestData) string { diff --git a/internal/services/signalr/web_pubsub_custom_certificate_resource.go b/internal/services/signalr/web_pubsub_custom_certificate_resource.go index ab99e0c447c9..7651c12818a2 100644 --- a/internal/services/signalr/web_pubsub_custom_certificate_resource.go +++ b/internal/services/signalr/web_pubsub_custom_certificate_resource.go @@ -122,7 +122,6 @@ func (r CustomCertWebPubsubResource) Create() sdk.ResourceFunc { } if keyVaultCertificateId.Version != "" { customCertObj.Properties.KeyVaultSecretVersion = utils.String(keyVaultCertificateId.Version) - } if err := client.CustomCertificatesCreateOrUpdateThenPoll(ctx, id, customCertObj); err != nil { diff --git a/internal/services/signalr/web_pubsub_custom_domain_resource_test.go b/internal/services/signalr/web_pubsub_custom_domain_resource_test.go index 0ea0d5b715df..f005ea235a64 100644 --- a/internal/services/signalr/web_pubsub_custom_domain_resource_test.go +++ b/internal/services/signalr/web_pubsub_custom_domain_resource_test.go @@ -60,7 +60,6 @@ func (r WebPubsubCustomDomainResource) Exists(ctx context.Context, client *clien return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } return utils.Bool(resp.Model != nil), nil - } func (r WebPubsubCustomDomainResource) basic(data acceptance.TestData) string { diff --git a/internal/services/springcloud/spring_cloud_application_insights_application_performance_monitoring_resource.go b/internal/services/springcloud/spring_cloud_application_insights_application_performance_monitoring_resource.go index a8d3a049a2a0..1304a92c184c 100644 --- a/internal/services/springcloud/spring_cloud_application_insights_application_performance_monitoring_resource.go +++ b/internal/services/springcloud/spring_cloud_application_insights_application_performance_monitoring_resource.go @@ -309,7 +309,6 @@ func (s SpringCloudApplicationInsightsApplicationPerformanceMonitoringResource) state.SamplingPercentage = samplingPercentage } } - } } diff --git a/internal/services/springcloud/spring_cloud_configuration_service_resource.go b/internal/services/springcloud/spring_cloud_configuration_service_resource.go index 4cdd9daa2b8f..8e30875a2abe 100644 --- a/internal/services/springcloud/spring_cloud_configuration_service_resource.go +++ b/internal/services/springcloud/spring_cloud_configuration_service_resource.go @@ -400,7 +400,6 @@ func flattenConfigurationServiceConfigurationServiceGitRepositoryArray(input *[] } for _, item := range *input { - var strictHostKeyChecking bool if item.StrictHostKeyChecking != nil { strictHostKeyChecking = *item.StrictHostKeyChecking diff --git a/internal/services/storage/blobs.go b/internal/services/storage/blobs.go index 95abec03616f..c5608518eb32 100644 --- a/internal/services/storage/blobs.go +++ b/internal/services/storage/blobs.go @@ -8,6 +8,7 @@ import ( "context" "encoding/base64" "encoding/hex" + "errors" "fmt" "io" "os" @@ -44,11 +45,11 @@ func (sbu BlobUpload) Create(ctx context.Context) error { if blobType == "append" { if sbu.Source != "" || sbu.SourceContent != "" || sbu.SourceUri != "" { - return fmt.Errorf("A source cannot be specified for an Append blob") + return errors.New("A source cannot be specified for an Append blob") } if sbu.ContentMD5 != "" { - return fmt.Errorf("`content_md5` cannot be specified for an Append blob") + return errors.New("`content_md5` cannot be specified for an Append blob") } return sbu.createEmptyAppendBlob(ctx) @@ -71,7 +72,7 @@ func (sbu BlobUpload) Create(ctx context.Context) error { if blobType == "page" { if sbu.ContentMD5 != "" { - return fmt.Errorf("`content_md5` cannot be specified for a Page blob") + return errors.New("`content_md5` cannot be specified for a Page blob") } if sbu.SourceUri != "" { return sbu.copy(ctx) @@ -86,7 +87,7 @@ func (sbu BlobUpload) Create(ctx context.Context) error { return sbu.createEmptyPageBlob(ctx) } - return fmt.Errorf("Unsupported Blob Type: %q", blobType) + return fmt.Errorf("unsupported Blob Type: %q", blobType) } func (sbu BlobUpload) copy(ctx context.Context) error { @@ -121,7 +122,7 @@ func (sbu BlobUpload) createEmptyAppendBlob(ctx context.Context) error { func (sbu BlobUpload) createEmptyBlockBlob(ctx context.Context) error { if sbu.ContentMD5 != "" { - return fmt.Errorf("`content_md5` cannot be specified for empty Block blobs") + return errors.New("`content_md5` cannot be specified for empty Block blobs") } input := blobs.PutBlockBlobInput{ @@ -180,7 +181,7 @@ func (sbu BlobUpload) uploadBlockBlob(ctx context.Context) error { func (sbu BlobUpload) createEmptyPageBlob(ctx context.Context) error { if sbu.Size == 0 { - return fmt.Errorf("`size` cannot be zero for a page blob") + return errors.New("`size` cannot be zero for a page blob") } input := blobs.PutPageBlobInput{ @@ -216,7 +217,7 @@ func (sbu BlobUpload) uploadPageBlobFromContent(ctx context.Context) error { func (sbu BlobUpload) uploadPageBlob(ctx context.Context) error { if sbu.Size != 0 { - return fmt.Errorf("`size` cannot be set for an uploaded page blob") + return errors.New("`size` cannot be set for an uploaded page blob") } // determine the details about the file @@ -349,7 +350,7 @@ func (sbu BlobUpload) storageBlobPageSplit(file io.ReaderAt, fileSize int64) ([] } } - var pages []storageBlobPage + pages := make([]storageBlobPage, 0, len(nonEmptyRanges)) for _, nonEmptyRange := range nonEmptyRanges { pages = append(pages, storageBlobPage{ offset: nonEmptyRange.offset, diff --git a/internal/services/storage/migration/account_v3_to_v4.go b/internal/services/storage/migration/account_v3_to_v4.go index 8fd9dc23854e..217bb81fe5b7 100644 --- a/internal/services/storage/migration/account_v3_to_v4.go +++ b/internal/services/storage/migration/account_v3_to_v4.go @@ -727,7 +727,6 @@ func (AccountV3ToV4) Schema() map[string]*pluginsdk.Schema { func (AccountV3ToV4) UpgradeFunc() pluginsdk.StateUpgraderFunc { return func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) { - if _, ok := rawState["cross_tenant_replication_enabled"]; !ok { rawState["cross_tenant_replication_enabled"] = true } diff --git a/internal/services/storage/parse/storage_table_entities.go b/internal/services/storage/parse/storage_table_entities.go index 5d4fa0caf755..f3f3d5dc810c 100644 --- a/internal/services/storage/parse/storage_table_entities.go +++ b/internal/services/storage/parse/storage_table_entities.go @@ -4,7 +4,7 @@ package parse import ( - "crypto/sha1" + "crypto/sha1" // nolint: gosec only used for hashing and the API expects sha1 "encoding/hex" "fmt" "strings" diff --git a/internal/services/storage/storage_account_local_user_resource.go b/internal/services/storage/storage_account_local_user_resource.go index 397289f7658d..eceabf4c93f4 100644 --- a/internal/services/storage/storage_account_local_user_resource.go +++ b/internal/services/storage/storage_account_local_user_resource.go @@ -5,6 +5,7 @@ package storage import ( "context" + "errors" "fmt" "strings" "time" @@ -222,9 +223,9 @@ func (r LocalUserResource) Create() sdk.ResourceFunc { // Sanity checks on input if plan.SshKeyEnabled != (len(plan.SshAuthorizedKey) != 0) { if plan.SshKeyEnabled { - return fmt.Errorf("`ssh_authorized_key` should be specified when `ssh_key_enabled` is enabled") + return errors.New("`ssh_authorized_key` should be specified when `ssh_key_enabled` is enabled") } else { - return fmt.Errorf("`ssh_authorized_key` should not be specified when `ssh_key_enabled` is disabled") + return errors.New("`ssh_authorized_key` should not be specified when `ssh_key_enabled` is disabled") } } @@ -451,8 +452,7 @@ func (r LocalUserResource) expandPermissionScopes(input []PermissionScopeModel) return nil } - var output []localusers.PermissionScope - + output := make([]localusers.PermissionScope, 0, len(input)) for _, v := range input { // The length constraint is guaranteed by schema permissions := v.Permissions[0] @@ -488,8 +488,7 @@ func (r LocalUserResource) flattenPermissionScopes(input *[]localusers.Permissio return nil } - var output []PermissionScopeModel - + output := make([]PermissionScopeModel, 0, len(*input)) for _, v := range *input { permissions := PermissionsModel{} // The Storage API's have a history of being case-insensitive, so we case-insensitively check the permission here. @@ -525,8 +524,7 @@ func (r LocalUserResource) expandSSHAuthorizedKeys(input []SshAuthorizedKeyModel return nil } - var output []localusers.SshPublicKey - + output := make([]localusers.SshPublicKey, 0, len(input)) for _, v := range input { output = append(output, localusers.SshPublicKey{ Description: pointer.To(v.Description), diff --git a/internal/services/storage/storage_account_resource.go b/internal/services/storage/storage_account_resource.go index 9c9fe9637835..ea95802cb2e9 100644 --- a/internal/services/storage/storage_account_resource.go +++ b/internal/services/storage/storage_account_resource.go @@ -5,6 +5,7 @@ package storage import ( "context" + "errors" "fmt" "log" "net/http" @@ -1118,10 +1119,10 @@ func resourceStorageAccount() *pluginsdk.Resource { if !features.FivePointOhBeta() && !v.(*clients.Client).Features.Storage.DataPlaneAvailable { if _, ok := d.GetOk("queue_properties"); ok { - return fmt.Errorf("cannot configure 'queue_properties' when the Provider Feature 'data_plane_available' is set to 'false'") + return errors.New("cannot configure 'queue_properties' when the Provider Feature 'data_plane_available' is set to 'false'") } if _, ok := d.GetOk("static_website"); ok { - return fmt.Errorf("cannot configure 'static_website' when the Provider Feature 'data_plane_available' is set to 'false'") + return errors.New("cannot configure 'static_website' when the Provider Feature 'data_plane_available' is set to 'false'") } } diff --git a/internal/services/storage/storage_containers_data_source.go b/internal/services/storage/storage_containers_data_source.go index ac2572ead3c0..b72165a2904f 100644 --- a/internal/services/storage/storage_containers_data_source.go +++ b/internal/services/storage/storage_containers_data_source.go @@ -140,7 +140,7 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { } func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, accountId accounts.AccountId, prefix string) []containerModel { - var output []containerModel + output := make([]containerModel, 0, len(l)) for _, item := range l { var name string if item.Name != nil { diff --git a/internal/services/storage/storage_queue_data_source.go b/internal/services/storage/storage_queue_data_source.go index 85077b4d3f13..4135bbef553f 100644 --- a/internal/services/storage/storage_queue_data_source.go +++ b/internal/services/storage/storage_queue_data_source.go @@ -65,7 +65,6 @@ func dataSourceStorageQueueRead(d *pluginsdk.ResourceData, meta interface{}) err queuesDataPlaneClient, err := storageClient.QueuesDataPlaneClient(ctx, *account, storageClient.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { return fmt.Errorf("building Queues Client: %v", err) - } // Determine the queue endpoint, so we can build a data plane ID diff --git a/internal/services/storage/storage_share_resource_test.go b/internal/services/storage/storage_share_resource_test.go index 0bca4e41aeb7..832930121a28 100644 --- a/internal/services/storage/storage_share_resource_test.go +++ b/internal/services/storage/storage_share_resource_test.go @@ -589,7 +589,6 @@ func (r StorageShareResource) Exists(ctx context.Context, client *clients.Client } return pointer.To(existing.Model != nil), nil - } // Destroy is deprecated for this resource. From 5.0 this will no longer use the Data Plane client. diff --git a/internal/services/storage/storage_table_data_source.go b/internal/services/storage/storage_table_data_source.go index d9fefb979dc6..749ba84896d5 100644 --- a/internal/services/storage/storage_table_data_source.go +++ b/internal/services/storage/storage_table_data_source.go @@ -167,7 +167,11 @@ func (k storageTableDataSource) Read() sdk.ResourceFunc { } func flattenStorageTableACLsWithMetadata(acls *[]tables.SignedIdentifier) []ACLModel { - var output []ACLModel + if acls == nil { + return []ACLModel{} + } + + output := make([]ACLModel, 0, len(*acls)) for _, acl := range *acls { var accessPolicies []AccessPolicyModel for _, policy := range []tables.AccessPolicy{acl.AccessPolicy} { diff --git a/internal/services/storagecache/hpc_cache.go b/internal/services/storagecache/hpc_cache.go index 7b9b4053b728..95d462d1f3af 100644 --- a/internal/services/storagecache/hpc_cache.go +++ b/internal/services/storagecache/hpc_cache.go @@ -34,7 +34,7 @@ func CacheDeleteAccessPolicyByName(policies []caches.NfsAccessPolicy, name strin } func CacheInsertOrUpdateAccessPolicy(policies []caches.NfsAccessPolicy, policy caches.NfsAccessPolicy) ([]caches.NfsAccessPolicy, error) { - var newPolicies []caches.NfsAccessPolicy + newPolicies := make([]caches.NfsAccessPolicy, 0, len(policies)) isNew := true for _, existPolicy := range policies { diff --git a/internal/services/storagecache/hpc_cache_resource.go b/internal/services/storagecache/hpc_cache_resource.go index 7d6adbcbcc3a..57e2353a0528 100644 --- a/internal/services/storagecache/hpc_cache_resource.go +++ b/internal/services/storagecache/hpc_cache_resource.go @@ -399,7 +399,7 @@ func flattenStorageCacheNfsDefaultAccessPolicy(input caches.NfsAccessPolicy) ([] } func expandStorageCacheNfsAccessRules(input []interface{}) []caches.NfsAccessRule { - var out []caches.NfsAccessRule + out := make([]caches.NfsAccessRule, 0, len(input)) for _, accessRuleRaw := range input { b := accessRuleRaw.(map[string]interface{}) out = append(out, caches.NfsAccessRule{ @@ -417,9 +417,8 @@ func expandStorageCacheNfsAccessRules(input []interface{}) []caches.NfsAccessRul } func flattenStorageCacheNfsAccessRules(input []caches.NfsAccessRule) ([]interface{}, error) { - var rules []interface{} + rules := make([]interface{}, 0, len(input)) for _, accessRule := range input { - anonymousUID := 0 if accessRule.AnonymousUID != nil { var err error diff --git a/internal/services/storagemover/storage_mover_source_endpoint_resource.go b/internal/services/storagemover/storage_mover_source_endpoint_resource.go index b1df2fc24095..c93dd5ad4174 100644 --- a/internal/services/storagemover/storage_mover_source_endpoint_resource.go +++ b/internal/services/storagemover/storage_mover_source_endpoint_resource.go @@ -138,7 +138,6 @@ func (r StorageMoverSourceEndpointResource) Create() sdk.ResourceFunc { v.Description = utils.String(model.Description) properties.Properties = v } - } if _, err := client.CreateOrUpdate(ctx, id, properties); err != nil { diff --git a/internal/services/subscription/validate/subscription_name.go b/internal/services/subscription/validate/subscription_name.go index ee57c6f78f14..131c058306b5 100644 --- a/internal/services/subscription/validate/subscription_name.go +++ b/internal/services/subscription/validate/subscription_name.go @@ -4,23 +4,24 @@ package validate import ( + "errors" "fmt" "regexp" ) -func SubscriptionName(i interface{}, k string) (warnings []string, errors []error) { +func SubscriptionName(i interface{}, k string) (warnings []string, errs []error) { v, ok := i.(string) if !ok { - errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + errs = append(errs, fmt.Errorf("expected type of %q to be string", k)) return } if len(v) > 64 || v == "" { - errors = append(errors, fmt.Errorf("Subscription Name must be between 1 and 64 characters in length")) + errs = append(errs, errors.New("Subscription Name must be between 1 and 64 characters in length")) } if regexp.MustCompile("[<>;|]").MatchString(v) { - errors = append(errors, fmt.Errorf("Subsciption Name cannot contain the characters `<`, `>`, `;`, or `|`")) + errs = append(errs, errors.New("Subsciption Name cannot contain the characters `<`, `>`, `;`, or `|`")) } return diff --git a/internal/services/synapse/client/client.go b/internal/services/synapse/client/client.go index 86b4b30b2773..2d57a7187a19 100644 --- a/internal/services/synapse/client/client.go +++ b/internal/services/synapse/client/client.go @@ -4,6 +4,7 @@ package client import ( + "errors" "fmt" "github.com/Azure/azure-sdk-for-go/services/preview/synapse/mgmt/v2.0/synapse" // nolint: staticcheck @@ -144,7 +145,7 @@ func NewClient(o *common.ClientOptions) *Client { func (client Client) RoleDefinitionsClient(workspaceName, synapseEndpointSuffix string) (*accesscontrol.RoleDefinitionsClient, error) { if client.synapseAuthorizer == nil { - return nil, fmt.Errorf("Synapse is not supported in this Azure Environment") + return nil, errors.New("Synapse is not supported in this Azure Environment") } endpoint := buildEndpoint(workspaceName, synapseEndpointSuffix) roleDefinitionsClient := accesscontrol.NewRoleDefinitionsClient(endpoint) @@ -154,7 +155,7 @@ func (client Client) RoleDefinitionsClient(workspaceName, synapseEndpointSuffix func (client Client) RoleAssignmentsClient(workspaceName, synapseEndpointSuffix string) (*accesscontrol.RoleAssignmentsClient, error) { if client.synapseAuthorizer == nil { - return nil, fmt.Errorf("Synapse is not supported in this Azure Environment") + return nil, errors.New("Synapse is not supported in this Azure Environment") } endpoint := buildEndpoint(workspaceName, synapseEndpointSuffix) roleAssignmentsClient := accesscontrol.NewRoleAssignmentsClient(endpoint) @@ -164,7 +165,7 @@ func (client Client) RoleAssignmentsClient(workspaceName, synapseEndpointSuffix func (client Client) ManagedPrivateEndpointsClient(workspaceName, synapseEndpointSuffix string) (*managedvirtualnetwork.ManagedPrivateEndpointsClient, error) { if client.synapseAuthorizer == nil { - return nil, fmt.Errorf("Synapse is not supported in this Azure Environment") + return nil, errors.New("Synapse is not supported in this Azure Environment") } endpoint := buildEndpoint(workspaceName, synapseEndpointSuffix) managedPrivateEndpointsClient := managedvirtualnetwork.NewManagedPrivateEndpointsClient(endpoint) @@ -174,7 +175,7 @@ func (client Client) ManagedPrivateEndpointsClient(workspaceName, synapseEndpoin func (client Client) LinkedServiceClient(workspaceName, synapseEndpointSuffix string) (*artifacts.LinkedServiceClient, error) { if client.synapseAuthorizer == nil { - return nil, fmt.Errorf("Synapse is not supported in this Azure Environment") + return nil, errors.New("Synapse is not supported in this Azure Environment") } endpoint := buildEndpoint(workspaceName, synapseEndpointSuffix) linkedServiceClient := artifacts.NewLinkedServiceClient(endpoint) diff --git a/internal/services/systemcentervirtualmachinemanager/system_center_virtual_machine_manager_server_resource.go b/internal/services/systemcentervirtualmachinemanager/system_center_virtual_machine_manager_server_resource.go index 49e57de62cc6..e45cf8b9f3b5 100644 --- a/internal/services/systemcentervirtualmachinemanager/system_center_virtual_machine_manager_server_resource.go +++ b/internal/services/systemcentervirtualmachinemanager/system_center_virtual_machine_manager_server_resource.go @@ -203,7 +203,6 @@ func (r SystemCenterVirtualMachineManagerServerResource) Read() sdk.ResourceFunc if v := model.Properties.Credentials; v != nil { state.Username = pointer.From(v.Username) } - } return metadata.Encode(&state) diff --git a/internal/services/trafficmanager/traffic_manager_profile_resource.go b/internal/services/trafficmanager/traffic_manager_profile_resource.go index 4e9461d2ba31..b7d779e9cd6b 100644 --- a/internal/services/trafficmanager/traffic_manager_profile_resource.go +++ b/internal/services/trafficmanager/traffic_manager_profile_resource.go @@ -4,6 +4,7 @@ package trafficmanager import ( + "errors" "fmt" "log" "strconv" @@ -244,12 +245,12 @@ func resourceArmTrafficManagerProfileCreate(d *pluginsdk.ResourceData, meta inte trafficRoutingMethodPtr := profile.Properties.TrafficRoutingMethod if *trafficRoutingMethodPtr == profiles.TrafficRoutingMethodMultiValue && profile.Properties.MaxReturn == nil { - return fmt.Errorf("`max_return` must be specified when `traffic_routing_method` is set to `MultiValue`") + return errors.New("`max_return` must be specified when `traffic_routing_method` is set to `MultiValue`") } if *profile.Properties.MonitorConfig.IntervalInSeconds == int64(10) && *profile.Properties.MonitorConfig.TimeoutInSeconds == int64(10) { - return fmt.Errorf("`timeout_in_seconds` must be between `5` and `9` when `interval_in_seconds` is set to `10`") + return errors.New("`timeout_in_seconds` must be between `5` and `9` when `interval_in_seconds` is set to `10`") } if _, err := client.CreateOrUpdate(ctx, id, profile); err != nil { diff --git a/internal/services/voiceservices/client/client.go b/internal/services/voiceservices/client/client.go index 13585656247a..489415146e1c 100644 --- a/internal/services/voiceservices/client/client.go +++ b/internal/services/voiceservices/client/client.go @@ -17,7 +17,6 @@ type Client struct { } func NewClient(o *common.ClientOptions) (*Client, error) { - communicationsGatewaysClient, err := communicationsgateways.NewCommunicationsGatewaysClientWithBaseURI(o.Environment.ResourceManager) if err != nil { return nil, fmt.Errorf("building Communications Gateways Client: %+v", err) diff --git a/internal/services/voiceservices/voice_services_communications_gateway_resource.go b/internal/services/voiceservices/voice_services_communications_gateway_resource.go index 28c4ae2889d5..043e29a95395 100644 --- a/internal/services/voiceservices/voice_services_communications_gateway_resource.go +++ b/internal/services/voiceservices/voice_services_communications_gateway_resource.go @@ -515,7 +515,7 @@ func expandCommunicationsPlatformModel(input []string) []communicationsgateways. return nil } - var output []communicationsgateways.CommunicationsPlatform + output := make([]communicationsgateways.CommunicationsPlatform, 0, len(input)) for _, v := range input { platform := communicationsgateways.CommunicationsPlatform(v) output = append(output, platform) diff --git a/internal/services/workloads/workloads_sap_single_node_virtual_instance_resource.go b/internal/services/workloads/workloads_sap_single_node_virtual_instance_resource.go index 930ad7a8f7ee..afa801274537 100644 --- a/internal/services/workloads/workloads_sap_single_node_virtual_instance_resource.go +++ b/internal/services/workloads/workloads_sap_single_node_virtual_instance_resource.go @@ -5,6 +5,7 @@ package workloads import ( "context" + "errors" "fmt" "time" @@ -405,7 +406,7 @@ func (r WorkloadsSAPSingleNodeVirtualInstanceResource) CustomizeDiff() sdk.Resou if v := rd.Get("single_server_configuration.0.disk_volume_configuration"); v != nil { diskVolumes := v.(*pluginsdk.Set).List() if hasDuplicateVolumeNameForSAPSingleNodeVirtualInstance(diskVolumes) { - return fmt.Errorf("`volume_name` cannot be duplicated") + return errors.New("`volume_name` cannot be duplicated") } } diff --git a/internal/services/workloads/workloads_sap_three_tier_virtual_instance_resource.go b/internal/services/workloads/workloads_sap_three_tier_virtual_instance_resource.go index 8f452f12163b..4df7e628a189 100644 --- a/internal/services/workloads/workloads_sap_three_tier_virtual_instance_resource.go +++ b/internal/services/workloads/workloads_sap_three_tier_virtual_instance_resource.go @@ -5,6 +5,7 @@ package workloads import ( "context" + "errors" "fmt" "time" @@ -1057,7 +1058,7 @@ func (r WorkloadsSAPThreeTierVirtualInstanceResource) CustomizeDiff() sdk.Resour if v := rd.Get("three_tier_configuration.0.database_server_configuration.0.disk_volume_configuration"); v != nil { diskVolumes := v.(*pluginsdk.Set).List() if hasDuplicateVolumeName(diskVolumes) { - return fmt.Errorf("`volume_name` cannot be duplicated") + return errors.New("`volume_name` cannot be duplicated") } } @@ -1937,7 +1938,7 @@ func flattenThreeTierConfiguration(input sapvirtualinstances.ThreeTierConfigurat } if _, ok := transportFileShareConfiguration.(sapvirtualinstances.MountFileShareConfiguration); ok { - return nil, fmt.Errorf("currently, the last segment of the Storage File Share resource manager ID in Swagger is defined as `/shares/` but it's unexpected. The last segment of the Storage File Share resource manager ID should be `/fileshares/` not `/shares/` in Swagger since the backend service is using `/fileshares/`. See more details from https://github.com/Azure/azure-rest-api-specs/issues/25209. So the feature of `TransportMount` isn't supported by TF for now due to this service API bug") + return nil, errors.New("currently, the last segment of the Storage File Share resource manager ID in Swagger is defined as `/shares/` but it's unexpected. The last segment of the Storage File Share resource manager ID should be `/fileshares/` not `/shares/` in Swagger since the backend service is using `/fileshares/`. See more details from https://github.com/Azure/azure-rest-api-specs/issues/25209. So the feature of `TransportMount` isn't supported by TF for now due to this service API bug") } } } diff --git a/internal/tools/document-lint/check/check_possible_value.go b/internal/tools/document-lint/check/check_possible_value.go index 8d98c8c6b067..6002eece3659 100644 --- a/internal/tools/document-lint/check/check_possible_value.go +++ b/internal/tools/document-lint/check/check_possible_value.go @@ -36,7 +36,7 @@ func newPossibleValueDiff(checkBase checkBase, want []string, got []string, miss } func possibleValueStr(values []string) string { - var codes []string + codes := make([]string, 0, len(values)) for _, val := range values { codes = append(codes, util.ItalicCode(val)) } diff --git a/internal/tools/document-lint/check/check_resource_all.go b/internal/tools/document-lint/check/check_resource_all.go index 5f4e8913631e..bcc76fd9aa5d 100644 --- a/internal/tools/document-lint/check/check_resource_all.go +++ b/internal/tools/document-lint/check/check_resource_all.go @@ -92,7 +92,6 @@ func (d *DiffResult) ToString() string { timeoutCount++ case forceNewDiff: forceNewCount++ - } } } diff --git a/internal/tools/document-lint/check/crossproperty.go b/internal/tools/document-lint/check/crossproperty.go index ab45d336f3da..eba16b07ad12 100644 --- a/internal/tools/document-lint/check/crossproperty.go +++ b/internal/tools/document-lint/check/crossproperty.go @@ -63,11 +63,11 @@ func shouldSkipDocProp(rt, path string) bool { func diffDocMiss(rt, path string, s *schema2.Schema, f *model.Field) (res []Checker) { // skip deprecated property if shouldSkipDocProp(rt, path) { - return + return res } if isSkipProp(rt, path) { - return + return res } if f == nil { @@ -93,7 +93,7 @@ func diffDocMiss(rt, path string, s *schema2.Schema, f *model.Field) (res []Chec case *schema2.Resource: if f.Subs == nil { res = append(res, newMissBlockDeclare(path, f)) - return + return res } for key, val := range ele.Schema { subField := f.Subs[key] @@ -120,10 +120,10 @@ func shouldSkipCodeProp(rt, path string) bool { func diffCodeMiss(rt, path string, f *model.Field, s *schema2.Schema) (res []Checker) { if shouldSkipCodeProp(rt, path) { - return + return res } if isSkipProp(rt, path) { - return + return res } if f != nil && f.FormatErr != "" { @@ -139,7 +139,7 @@ func diffCodeMiss(rt, path string, f *model.Field, s *schema2.Schema) (res []Che } else { res = append(res, newFormatErr(f.Content, f.FormatErr, newCheckBase(f.Line, path, f))) } - return + return res } if s == nil { diff --git a/internal/tools/document-lint/check/document_fixer.go b/internal/tools/document-lint/check/document_fixer.go index cffd5aee646c..48242ebe5100 100644 --- a/internal/tools/document-lint/check/document_fixer.go +++ b/internal/tools/document-lint/check/document_fixer.go @@ -94,11 +94,11 @@ func tryFixTimeouts(rt string, lines []string, diffs []TimeoutDiffItem) []string func (f *Fixer) TryFix() (err error) { // read file as bytes if len(f.Diff) == 0 { - return + return err } if d, ok := f.Diff[0].(diffWithMessage); ok { log.Printf("%s: %s", f.ResourceType, d.msg) - return + return err } content, err := os.ReadFile(f.MDFile) if err != nil { diff --git a/internal/tools/document-lint/md/normalize.go b/internal/tools/document-lint/md/normalize.go index d3ccb80155b8..786aacaaba7a 100644 --- a/internal/tools/document-lint/md/normalize.go +++ b/internal/tools/document-lint/md/normalize.go @@ -99,9 +99,10 @@ func FixFileNormalize(file string) { lines := strings.Split(content, "\n") var curScope model.PosType - var newContent []string var skipThisLine int var inHCL bool + + newContent := make([]string, 0, len(lines)) for idx, line := range lines { if inHCL { newContent = append(newContent, line) diff --git a/internal/tools/document-lint/md/parse_md_test.go b/internal/tools/document-lint/md/parse_md_test.go index 28d421cfda4a..cedfb1cd0895 100644 --- a/internal/tools/document-lint/md/parse_md_test.go +++ b/internal/tools/document-lint/md/parse_md_test.go @@ -35,6 +35,5 @@ func Test_unmarshalFile(t *testing.T) { if gotArgs := len(doc.Args); gotArgs != arg.argsNum { t.Fatalf("`%s` expect arg num: %d, got: %d", arg.file, gotArgs, arg.argsNum) } - } } diff --git a/internal/tools/document-lint/md/resource_doc.go b/internal/tools/document-lint/md/resource_doc.go index 32d0b1278127..a9624e243e0e 100644 --- a/internal/tools/document-lint/md/resource_doc.go +++ b/internal/tools/document-lint/md/resource_doc.go @@ -75,7 +75,7 @@ func extractFieldFromLine(line string) (field *model.Field) { if len(res) <= 1 || res[1] == "" { field.Name = util.FirstCodeValue(line) // try to use the first code as name field.FormatErr = "no field name found" - return + return field } field.Name = res[1] if field.Name == "" { diff --git a/internal/tools/document-lint/util/string_test.go b/internal/tools/document-lint/util/string_test.go index 5e92138dd6eb..688fea89f69e 100644 --- a/internal/tools/document-lint/util/string_test.go +++ b/internal/tools/document-lint/util/string_test.go @@ -59,5 +59,4 @@ func TestTimeoutIdx(t *testing.T) { line = "* `delete` - (Defaults to 30 minutes) Used when deleting the EventGrid Event Subscription." idxs = timeoutValueReg.FindStringSubmatchIndex(line) t.Logf("%v: %s", idxs, line[idxs[0]:idxs[1]]) - } diff --git a/internal/tools/generator-resource-id/main.go b/internal/tools/generator-resource-id/main.go index 2b2baf800313..3d07647e4f32 100644 --- a/internal/tools/generator-resource-id/main.go +++ b/internal/tools/generator-resource-id/main.go @@ -395,7 +395,6 @@ func New%[1]sID(%[2]s string) %[1]sId { func (id ResourceIdGenerator) codeForDescription() string { makeHumanReadable := func(input string) string { - chars := make([]rune, 0) for i, c := range input { if unicode.IsUpper(c) && i+1 < len(input) && unicode.IsLower(rune(input[i+1])) { diff --git a/internal/tools/generator-services/main.go b/internal/tools/generator-services/main.go index 8de0fe2cc4a7..5483ae7448aa 100644 --- a/internal/tools/generator-services/main.go +++ b/internal/tools/generator-services/main.go @@ -288,7 +288,6 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct label := "" for _, service := range provider.SupportedTypedServices() { - v, ok := service.(sdk.TypedServiceRegistrationWithAGitHubLabel) // keep a record of resources/datasources that don't have labels so they can be used to check that prefixes generated later don't match resources from those services if ok { @@ -305,7 +304,6 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct } labelToNames = appendToSliceWithinMap(labelToNames, names, label) - } for _, service := range provider.SupportedUntypedServices() { v, ok := service.(sdk.UntypedServiceRegistrationWithAGitHubLabel) @@ -332,7 +330,6 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct names = removeDuplicateNames(names) labelToNames = appendToSliceWithinMap(labelToNames, names, label) - } sortedLabels := make([]string, 0) @@ -347,7 +344,6 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct // loop through all labels and get a list of prefixes that match each label. And for each prefix, record which resource/datasource names it is derived from - we need to retain these in case there are duplicate prefixes matching resources with a different label for _, labelName := range sortedLabels { - longestPrefix := longestCommonPrefix(labelToNames[labelName]) var prefixGroups []Prefix // If there is no common prefix for a service, separate it into groups using the next segment of the name (azurerm_xxx) and add multiple possible prefixes for the label @@ -366,12 +362,10 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct } } labelToPrefixes[labelName] = prefixGroups - } // loop though again, this time compiling prefixes into a regex for each label and separating out duplicates for _, labelName := range sortedLabels { - if labelName == "" { continue } @@ -384,7 +378,6 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct for _, prefix := range labelToPrefixes[labelName] { // if a prefix matches another prefix, use the whole name for each resource/ds that matches that prefix in the regex if prefixHasMatch(labelName, prefix, labelToPrefixes) { - for _, name := range prefix.Names { prefixes = append(prefixes, strings.TrimPrefix(name+"\\W+", azurerm)) } @@ -457,7 +450,6 @@ func longestCommonPrefix(names []string) string { end := false if len(names) > 0 { - sort.Strings(names) first := names[0] last := names[len(names)-1] @@ -525,10 +517,9 @@ func prefixHasMatch(labelToCheck string, prefixToCheck Prefix, labelToPrefixes m } func getPrefixesForNames(names []string) []Prefix { - - var prefixes []Prefix groupedNames := commonPrefixGroups(names) + prefixes := make([]Prefix, 0, len(groupedNames)) for _, group := range groupedNames { prefix := Prefix{ Names: group, diff --git a/internal/tools/static-analysis/rules/typed_sdk_bit_check.go b/internal/tools/static-analysis/rules/typed_sdk_bit_check.go index 84fe50a966c9..e02bd6346f01 100644 --- a/internal/tools/static-analysis/rules/typed_sdk_bit_check.go +++ b/internal/tools/static-analysis/rules/typed_sdk_bit_check.go @@ -34,7 +34,6 @@ func (r TypedSDKBitCheck) Run() (errors []error) { default: errors = append(errors, fmt.Errorf("%q cannot be bit checked, ModelObject did not return a pointer\n", resource.ResourceType())) } - } for _, datasource := range s.DataSources() { modelType := reflect.TypeOf(datasource.ModelObject()) diff --git a/internal/tools/update-api-version/main.go b/internal/tools/update-api-version/main.go index f188864d2bf7..d2031e1ee7d7 100644 --- a/internal/tools/update-api-version/main.go +++ b/internal/tools/update-api-version/main.go @@ -113,7 +113,7 @@ func updateImportsWithinDirectory(serviceName string, oldApiVersion string, newA if err = format.Node(&buf, fileSet, file); err != nil { return fmt.Errorf("error formatting new code: %w", err) } - _ = os.WriteFile(fileName, buf.Bytes(), 0644) + _ = os.WriteFile(fileName, buf.Bytes(), 0600) } } return nil