From bccc83d64b061f9e16e0d90b794819e90fc8ad22 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Fri, 21 Feb 2020 16:25:59 -0800 Subject: [PATCH 1/4] removing deprecated resources --- .../data_source_builtin_role_definition.go | 190 --- .../services/authorization/registration.go | 5 +- ...ata_source_builtin_role_definition_test.go | 112 -- .../resource_arm_role_assignment_test.go | 8 +- .../internal/services/monitor/registration.go | 5 +- .../monitor/resource_arm_autoscale_setting.go | 1087 ----------------- .../monitor/resource_arm_metric_alertrule.go | 476 -------- .../resource_arm_monitor_metric_alertrule.go | 462 ------- .../resource_arm_autoscale_setting_test.go | 918 -------------- .../resource_arm_metric_alertrule_test.go | 483 -------- ...ource_arm_monitor_metric_alertrule_test.go | 462 ------- ...source_private_link_endpoint_connection.go | 167 --- .../internal/services/network/registration.go | 4 - .../resource_arm_connection_monitor.go | 351 ------ .../resource_arm_ddos_protection_plan.go | 254 ---- ...source_arm_network_ddos_protection_plan.go | 20 + .../resource_arm_private_link_endpoint.go | 242 ---- ...e_private_link_endpoint_connection_test.go | 37 - .../resource_arm_connection_monitor_test.go | 648 ---------- .../resource_arm_ddos_protection_plan_test.go | 264 ---- ...resource_arm_private_link_endpoint_test.go | 102 -- .../resource_arm_virtual_network_test.go | 4 +- ..._vm.go => data_source_backup_policy_vm.go} | 12 +- .../services/recoveryservices/registration.go | 36 +- .../resource_arm_recovery_services_fabric.go | 164 --- ...e_arm_recovery_services_network_mapping.go | 216 ---- ...urce_arm_recovery_services_protected_vm.go | 283 ----- ..._recovery_services_protection_container.go | 162 --- ...y_services_protection_container_mapping.go | 203 --- ..._recovery_services_protection_policy_vm.go | 764 ------------ ...rce_arm_recovery_services_replicated_vm.go | 353 ------ ...rm_recovery_services_replication_policy.go | 215 ---- ..._arm_site_recovery_protection_container.go | 2 +- ...o => data_source_backup_policy_vm_test.go} | 18 +- ...ource_arm_recovery_services_fabric_test.go | 113 -- ..._recovery_services_network_mapping_test.go | 161 --- ...arm_recovery_services_protected_vm_test.go | 642 ---------- ...vices_protection_container_mapping_test.go | 158 --- ...very_services_protection_container_test.go | 121 -- ...very_services_protection_policy_vm_test.go | 555 --------- ...rm_recovery_services_replicated_vm_test.go | 269 ---- ...covery_services_replication_policy_test.go | 113 -- .../autoscale/main.tf | 2 +- website/azurerm.erb | 71 +- ..._vm.markdown => backup_policy_vm.markdown} | 14 +- .../docs/d/builtin_role_definition.markdown | 51 - ...ate_link_endpoint_connection.html.markdown | 61 - website/docs/d/role_definition.html.markdown | 2 +- .../guides/2.0-upgrade-guide.html.markdown | 10 + .../managed_service_identity.html.markdown | 4 +- .../docs/r/autoscale_setting.html.markdown | 421 ------- .../docs/r/connection_monitor.html.markdown | 181 --- .../docs/r/ddos_protection_plan.html.markdown | 68 -- website/docs/r/metric_alertrule.html.markdown | 167 --- .../r/monitor_metric_alertrule.html.markdown | 165 --- .../network_connection_monitor.html.markdown | 179 --- .../r/private_link_endpoint.html.markdown | 162 --- .../r/recovery_network_mapping.html.markdown | 114 -- .../r/recovery_services_fabric.html.markdown | 76 -- .../r/recovery_services_protected_vm.markdown | 87 -- ...ervices_protection_container.html.markdown | 83 -- ...protection_container_mapping.html.markdown | 121 -- ...ery_services_protection_policy_vm.markdown | 159 --- ...overy_services_replicated_vm.html.markdown | 232 ---- ..._services_replication_policy.html.markdown | 74 -- website/docs/r/virtual_network.html.markdown | 4 +- 66 files changed, 86 insertions(+), 13283 deletions(-) delete mode 100644 azurerm/internal/services/authorization/data_source_builtin_role_definition.go delete mode 100644 azurerm/internal/services/authorization/tests/data_source_builtin_role_definition_test.go delete mode 100644 azurerm/internal/services/monitor/resource_arm_autoscale_setting.go delete mode 100644 azurerm/internal/services/monitor/resource_arm_metric_alertrule.go delete mode 100644 azurerm/internal/services/monitor/resource_arm_monitor_metric_alertrule.go delete mode 100644 azurerm/internal/services/monitor/tests/resource_arm_autoscale_setting_test.go delete mode 100644 azurerm/internal/services/monitor/tests/resource_arm_metric_alertrule_test.go delete mode 100644 azurerm/internal/services/monitor/tests/resource_arm_monitor_metric_alertrule_test.go delete mode 100644 azurerm/internal/services/network/data_source_private_link_endpoint_connection.go delete mode 100644 azurerm/internal/services/network/resource_arm_connection_monitor.go delete mode 100644 azurerm/internal/services/network/resource_arm_ddos_protection_plan.go delete mode 100644 azurerm/internal/services/network/resource_arm_private_link_endpoint.go delete mode 100644 azurerm/internal/services/network/tests/data_source_private_link_endpoint_connection_test.go delete mode 100644 azurerm/internal/services/network/tests/resource_arm_connection_monitor_test.go delete mode 100644 azurerm/internal/services/network/tests/resource_arm_ddos_protection_plan_test.go delete mode 100644 azurerm/internal/services/network/tests/resource_arm_private_link_endpoint_test.go rename azurerm/internal/services/recoveryservices/{data_source_recovery_services_protection_policy_vm.go => data_source_backup_policy_vm.go} (72%) delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_fabric.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_network_mapping.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protected_vm.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container_mapping.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_policy_vm.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replicated_vm.go delete mode 100644 azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replication_policy.go rename azurerm/internal/services/recoveryservices/tests/{data_source_recovery_services_protection_policy_vm_test.go => data_source_backup_policy_vm_test.go} (53%) delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_fabric_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_network_mapping_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protected_vm_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_mapping_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_policy_vm_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replicated_vm_test.go delete mode 100644 azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replication_policy_test.go rename website/docs/d/{recovery_services_protection_policy_vm.markdown => backup_policy_vm.markdown} (62%) delete mode 100644 website/docs/d/builtin_role_definition.markdown delete mode 100644 website/docs/d/private_link_endpoint_connection.html.markdown delete mode 100644 website/docs/r/autoscale_setting.html.markdown delete mode 100644 website/docs/r/connection_monitor.html.markdown delete mode 100644 website/docs/r/ddos_protection_plan.html.markdown delete mode 100644 website/docs/r/metric_alertrule.html.markdown delete mode 100644 website/docs/r/monitor_metric_alertrule.html.markdown delete mode 100644 website/docs/r/network_connection_monitor.html.markdown delete mode 100644 website/docs/r/private_link_endpoint.html.markdown delete mode 100644 website/docs/r/recovery_network_mapping.html.markdown delete mode 100644 website/docs/r/recovery_services_fabric.html.markdown delete mode 100644 website/docs/r/recovery_services_protected_vm.markdown delete mode 100644 website/docs/r/recovery_services_protection_container.html.markdown delete mode 100644 website/docs/r/recovery_services_protection_container_mapping.html.markdown delete mode 100644 website/docs/r/recovery_services_protection_policy_vm.markdown delete mode 100644 website/docs/r/recovery_services_replicated_vm.html.markdown delete mode 100644 website/docs/r/recovery_services_replication_policy.html.markdown diff --git a/azurerm/internal/services/authorization/data_source_builtin_role_definition.go b/azurerm/internal/services/authorization/data_source_builtin_role_definition.go deleted file mode 100644 index 3c47827503a1..000000000000 --- a/azurerm/internal/services/authorization/data_source_builtin_role_definition.go +++ /dev/null @@ -1,190 +0,0 @@ -package authorization - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-09-01-preview/authorization" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" -) - -func dataSourceArmBuiltInRoleDefinition() *schema.Resource { - return &schema.Resource{ - Read: dataSourceArmBuiltInRoleDefinitionRead, - - Timeouts: &schema.ResourceTimeout{ - Read: schema.DefaultTimeout(5 * time.Minute), - }, - - DeprecationMessage: `This Data Source has been deprecated in favour of the 'azurerm_role_definition' resource that now can look up role definitions by names. - -As such this Data Source will be removed in v2.0 of the AzureRM Provider. -`, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - - // Computed - "description": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "permissions": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "actions": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "not_actions": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "data_actions": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Set: schema.HashString, - }, - "not_data_actions": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Set: schema.HashString, - }, - }, - }, - }, - "assignable_scopes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - } -} - -func dataSourceArmBuiltInRoleDefinitionRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Authorization.RoleDefinitionsClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - name := d.Get("name").(string) - if name == "VirtualMachineContributor" { - name = "Virtual Machine Contributor" - } - filter := fmt.Sprintf("roleName eq '%s'", name) - roleDefinitions, err := client.List(ctx, "", filter) - if err != nil { - return fmt.Errorf("Error loading Role Definition List: %+v", err) - } - if len(roleDefinitions.Values()) != 1 { - return fmt.Errorf("Error loading Role Definition List: could not find role '%s'", name) - } - - roleDefinitionId := *roleDefinitions.Values()[0].ID - - d.SetId(roleDefinitionId) - - role, err := client.GetByID(ctx, roleDefinitionId) - if err != nil { - return fmt.Errorf("Error loading Role Definition: %+v", err) - } - - if props := role.RoleDefinitionProperties; props != nil { - d.Set("name", props.RoleName) - d.Set("description", props.Description) - d.Set("type", props.RoleType) - - permissions := flattenRoleDefinitionDataSourcePermissions(props.Permissions) - if err := d.Set("permissions", permissions); err != nil { - return err - } - - assignableScopes := flattenRoleDefinitionDataSourceAssignableScopes(props.AssignableScopes) - if err := d.Set("assignable_scopes", assignableScopes); err != nil { - return err - } - } - - return nil -} - -func flattenRoleDefinitionDataSourcePermissions(input *[]authorization.Permission) []interface{} { - permissions := make([]interface{}, 0) - if input == nil { - return permissions - } - - for _, permission := range *input { - output := make(map[string]interface{}) - - actions := make([]string, 0) - if s := permission.Actions; s != nil { - actions = *s - } - output["actions"] = actions - - dataActions := make([]interface{}, 0) - if s := permission.DataActions; s != nil { - for _, dataAction := range *s { - dataActions = append(dataActions, dataAction) - } - } - output["data_actions"] = schema.NewSet(schema.HashString, dataActions) - - notActions := make([]string, 0) - if s := permission.NotActions; s != nil { - notActions = *s - } - output["not_actions"] = notActions - - notDataActions := make([]interface{}, 0) - if s := permission.NotDataActions; s != nil { - for _, dataAction := range *s { - notDataActions = append(notDataActions, dataAction) - } - } - output["not_data_actions"] = schema.NewSet(schema.HashString, notDataActions) - - permissions = append(permissions, output) - } - - return permissions -} - -func flattenRoleDefinitionDataSourceAssignableScopes(input *[]string) []interface{} { - scopes := make([]interface{}, 0) - if input == nil { - return scopes - } - - for _, scope := range *input { - scopes = append(scopes, scope) - } - - return scopes -} diff --git a/azurerm/internal/services/authorization/registration.go b/azurerm/internal/services/authorization/registration.go index b40308564674..9fd6e42c3dd9 100644 --- a/azurerm/internal/services/authorization/registration.go +++ b/azurerm/internal/services/authorization/registration.go @@ -21,9 +21,8 @@ func (r Registration) WebsiteCategories() []string { // SupportedDataSources returns the supported Data Sources supported by this Service func (r Registration) SupportedDataSources() map[string]*schema.Resource { return map[string]*schema.Resource{ - "azurerm_builtin_role_definition": dataSourceArmBuiltInRoleDefinition(), - "azurerm_client_config": dataSourceArmClientConfig(), - "azurerm_role_definition": dataSourceArmRoleDefinition(), + "azurerm_client_config": dataSourceArmClientConfig(), + "azurerm_role_definition": dataSourceArmRoleDefinition(), } } diff --git a/azurerm/internal/services/authorization/tests/data_source_builtin_role_definition_test.go b/azurerm/internal/services/authorization/tests/data_source_builtin_role_definition_test.go deleted file mode 100644 index 805b443e014c..000000000000 --- a/azurerm/internal/services/authorization/tests/data_source_builtin_role_definition_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" -) - -func TestAccDataSourceAzureRMBuiltInRoleDefinition_contributor(t *testing.T) { - data := acceptance.BuildTestData(t, "data.azurerm_builtin_role_definition", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourceBuiltInRoleDefinition("Contributor"), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(data.ResourceName, "id", "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"), - resource.TestCheckResourceAttrSet(data.ResourceName, "description"), - resource.TestCheckResourceAttrSet(data.ResourceName, "type"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.0", "*"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.#", "5"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.0", "Microsoft.Authorization/*/Delete"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.1", "Microsoft.Authorization/*/Write"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.2", "Microsoft.Authorization/elevateAccess/Action"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.3", "Microsoft.Blueprint/blueprintAssignments/write"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.4", "Microsoft.Blueprint/blueprintAssignments/delete"), - ), - }, - }, - }) -} - -func TestAccDataSourceAzureRMBuiltInRoleDefinition_owner(t *testing.T) { - data := acceptance.BuildTestData(t, "data.azurerm_builtin_role_definition", "test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourceBuiltInRoleDefinition("Owner"), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(data.ResourceName, "id", "/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"), - resource.TestCheckResourceAttrSet(data.ResourceName, "description"), - resource.TestCheckResourceAttrSet(data.ResourceName, "type"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.0", "*"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.#", "0"), - ), - }, - }, - }) -} - -func TestAccDataSourceAzureRMBuiltInRoleDefinition_reader(t *testing.T) { - data := acceptance.BuildTestData(t, "data.azurerm_builtin_role_definition", "test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourceBuiltInRoleDefinition("Reader"), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(data.ResourceName, "id", "/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"), - resource.TestCheckResourceAttrSet(data.ResourceName, "description"), - resource.TestCheckResourceAttrSet(data.ResourceName, "type"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.0", "*/read"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.#", "0"), - ), - }, - }, - }) -} - -func TestAccDataSourceAzureRMBuiltInRoleDefinition_virtualMachineContributor(t *testing.T) { - data := acceptance.BuildTestData(t, "data.azurerm_builtin_role_definition", "test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourceBuiltInRoleDefinition("VirtualMachineContributor"), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(data.ResourceName, "id", "/providers/Microsoft.Authorization/roleDefinitions/9980e02c-c2be-4d73-94e8-173b1dc7cf3c"), - resource.TestCheckResourceAttrSet(data.ResourceName, "description"), - resource.TestCheckResourceAttrSet(data.ResourceName, "type"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.#", "38"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.0", "Microsoft.Authorization/*/read"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.actions.15", "Microsoft.Network/networkSecurityGroups/join/action"), - resource.TestCheckResourceAttr(data.ResourceName, "permissions.0.not_actions.#", "0"), - ), - }, - }, - }) -} - -func testAccDataSourceBuiltInRoleDefinition(name string) string { - return fmt.Sprintf(` -data "azurerm_builtin_role_definition" "test" { - name = "%s" -} -`, name) -} diff --git a/azurerm/internal/services/authorization/tests/resource_arm_role_assignment_test.go b/azurerm/internal/services/authorization/tests/resource_arm_role_assignment_test.go index 0b30cb6b1edd..df2e193fe5e2 100644 --- a/azurerm/internal/services/authorization/tests/resource_arm_role_assignment_test.go +++ b/azurerm/internal/services/authorization/tests/resource_arm_role_assignment_test.go @@ -342,13 +342,13 @@ data "azurerm_subscription" "primary" {} data "azurerm_client_config" "test" {} -data "azurerm_builtin_role_definition" "test" { +data "azurerm_role_definition" "test" { name = "Monitoring Reader" } resource "azurerm_role_assignment" "test" { scope = "${data.azurerm_subscription.primary.id}" - role_definition_id = "${data.azurerm_subscription.primary.id}${data.azurerm_builtin_role_definition.test.id}" + role_definition_id = "${data.azurerm_subscription.primary.id}${data.azurerm_role_definition.test.id}" principal_id = "${data.azurerm_client_config.test.service_principal_object_id}" } ` @@ -403,14 +403,14 @@ data "azurerm_subscription" "primary" {} data "azurerm_client_config" "test" {} -data "azurerm_builtin_role_definition" "test" { +data "azurerm_role_definition" "test" { name = "Site Recovery Reader" } resource "azurerm_role_assignment" "test" { name = "%s" scope = "${data.azurerm_subscription.primary.id}" - role_definition_id = "${data.azurerm_subscription.primary.id}${data.azurerm_builtin_role_definition.test.id}" + role_definition_id = "${data.azurerm_subscription.primary.id}${data.azurerm_role_definition.test.id}" principal_id = "${data.azurerm_client_config.test.service_principal_object_id}" } `, id) diff --git a/azurerm/internal/services/monitor/registration.go b/azurerm/internal/services/monitor/registration.go index 691f4f753c25..b1ccab0aef1a 100644 --- a/azurerm/internal/services/monitor/registration.go +++ b/azurerm/internal/services/monitor/registration.go @@ -29,13 +29,10 @@ func (r Registration) SupportedDataSources() map[string]*schema.Resource { // SupportedResources returns the supported Resources supported by this Service func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ - "azurerm_autoscale_setting": resourceArmAutoScaleSetting(), - "azurerm_metric_alertrule": resourceArmMetricAlertRule(), "azurerm_monitor_autoscale_setting": resourceArmMonitorAutoScaleSetting(), "azurerm_monitor_action_group": resourceArmMonitorActionGroup(), "azurerm_monitor_activity_log_alert": resourceArmMonitorActivityLogAlert(), "azurerm_monitor_diagnostic_setting": resourceArmMonitorDiagnosticSetting(), "azurerm_monitor_log_profile": resourceArmMonitorLogProfile(), - "azurerm_monitor_metric_alert": resourceArmMonitorMetricAlert(), - "azurerm_monitor_metric_alertrule": resourceArmMonitorMetricAlertRule()} + "azurerm_monitor_metric_alert": resourceArmMonitorMetricAlert()} } diff --git a/azurerm/internal/services/monitor/resource_arm_autoscale_setting.go b/azurerm/internal/services/monitor/resource_arm_autoscale_setting.go deleted file mode 100644 index 636fe22e6522..000000000000 --- a/azurerm/internal/services/monitor/resource_arm_autoscale_setting.go +++ /dev/null @@ -1,1087 +0,0 @@ -package monitor - -import ( - "fmt" - "log" - "strconv" - "time" - - "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights" - "github.com/Azure/go-autorest/autorest/date" - "github.com/hashicorp/go-azure-helpers/response" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmAutoScaleSetting() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: `The 'azurerm_autoscale_setting' resource is deprecated in favour of the renamed version 'azurerm_monitor_autoscale_setting'. - -Information on migrating to the renamed resource can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-between-renamed-resources.html - -As such the existing 'azurerm_autoscale_setting' resource is deprecated and will be removed in the next major version of the AzureRM Provider (2.0). -`, - - Create: resourceArmAutoScaleSettingCreateUpdate, - Read: resourceArmAutoScaleSettingRead, - Update: resourceArmAutoScaleSettingCreateUpdate, - Delete: resourceArmAutoScaleSettingDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - - "resource_group_name": azure.SchemaResourceGroupName(), - - "location": azure.SchemaLocation(), - - "target_resource_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - }, - - "enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - - "profile": { - Type: schema.TypeList, - Required: true, - MaxItems: 20, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "capacity": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "minimum": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(0, 1000), - }, - "maximum": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(0, 1000), - }, - "default": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(0, 1000), - }, - }, - }, - }, - "rule": { - Type: schema.TypeList, - Optional: true, - MaxItems: 10, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metric_trigger": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metric_name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "metric_resource_id": { - Type: schema.TypeString, - Required: true, - ValidateFunc: azure.ValidateResourceID, - }, - "time_grain": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.ISO8601Duration, - }, - "statistic": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.MetricStatisticTypeAverage), - string(insights.MetricStatisticTypeMax), - string(insights.MetricStatisticTypeMin), - string(insights.MetricStatisticTypeSum), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - "time_window": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.ISO8601Duration, - }, - "time_aggregation": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.TimeAggregationTypeAverage), - string(insights.TimeAggregationTypeCount), - string(insights.TimeAggregationTypeMaximum), - string(insights.TimeAggregationTypeMinimum), - string(insights.TimeAggregationTypeTotal), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - "operator": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.Equals), - string(insights.GreaterThan), - string(insights.GreaterThanOrEqual), - string(insights.LessThan), - string(insights.LessThanOrEqual), - string(insights.NotEquals), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - "threshold": { - Type: schema.TypeFloat, - Required: true, - }, - }, - }, - }, - "scale_action": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "direction": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.ScaleDirectionDecrease), - string(insights.ScaleDirectionIncrease), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - "type": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.ChangeCount), - string(insights.ExactCount), - string(insights.PercentChangeCount), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - "value": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntAtLeast(0), - }, - "cooldown": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.ISO8601Duration, - }, - }, - }, - }, - }, - }, - }, - "fixed_date": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "timezone": { - Type: schema.TypeString, - Optional: true, - Default: "UTC", - ValidateFunc: validateAutoScaleSettingsTimeZone(), - }, - "start": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.RFC3339Time, - }, - "end": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.RFC3339Time, - }, - }, - }, - }, - "recurrence": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "timezone": { - Type: schema.TypeString, - Optional: true, - Default: "UTC", - ValidateFunc: validateAutoScaleSettingsTimeZone(), - }, - "days": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.StringInSlice([]string{ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday", - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - }, - "hours": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Schema{ - Type: schema.TypeInt, - ValidateFunc: validation.IntBetween(0, 23), - }, - }, - "minutes": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Schema{ - Type: schema.TypeInt, - ValidateFunc: validation.IntBetween(0, 59), - }, - }, - }, - }, - }, - }, - }, - }, - - "notification": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "email": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "send_to_subscription_administrator": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "send_to_subscription_co_administrator": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "custom_emails": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - "webhook": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "service_uri": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "properties": { - Type: schema.TypeMap, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - }, - }, - }, - - "tags": tags.Schema(), - }, - } -} - -func resourceArmAutoScaleSettingCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AutoscaleSettingsClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing AutoScale Setting %q (Resource Group %q): %s", name, resourceGroup, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_autoscale_setting", *existing.ID) - } - } - - location := azure.NormalizeLocation(d.Get("location").(string)) - enabled := d.Get("enabled").(bool) - targetResourceId := d.Get("target_resource_id").(string) - - notificationsRaw := d.Get("notification").([]interface{}) - notifications := expandAzureRmAutoScaleSettingNotifications(notificationsRaw) - - profilesRaw := d.Get("profile").([]interface{}) - profiles, err := expandAzureRmAutoScaleSettingProfile(profilesRaw) - if err != nil { - return fmt.Errorf("Error expanding `profile`: %+v", err) - } - - t := d.Get("tags").(map[string]interface{}) - expandedTags := tags.Expand(t) - - parameters := insights.AutoscaleSettingResource{ - Location: utils.String(location), - AutoscaleSetting: &insights.AutoscaleSetting{ - Enabled: &enabled, - Profiles: profiles, - Notifications: notifications, - TargetResourceURI: &targetResourceId, - }, - Tags: expandedTags, - } - - if _, err = client.CreateOrUpdate(ctx, resourceGroup, name, parameters); err != nil { - return fmt.Errorf("Error creating AutoScale Setting %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - read, err := client.Get(ctx, resourceGroup, name) - if err != nil { - return fmt.Errorf("Error retrieving AutoScale Setting %q (Resource Group %q): %+v", name, resourceGroup, err) - } - if read.ID == nil { - return fmt.Errorf("AutoScale Setting %q (Resource Group %q) has no ID", name, resourceGroup) - } - - d.SetId(*read.ID) - - return resourceArmAutoScaleSettingRead(d, meta) -} - -func resourceArmAutoScaleSettingRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AutoscaleSettingsClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["autoscalesettings"] - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] AutoScale Setting %q (Resource Group %q) was not found - removing from state!", name, resourceGroup) - d.SetId("") - return nil - } - - return fmt.Errorf("Error reading AutoScale Setting %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - d.Set("name", name) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - d.Set("enabled", resp.Enabled) - d.Set("target_resource_id", resp.TargetResourceURI) - - profile, err := flattenAzureRmAutoScaleSettingProfile(resp.Profiles) - if err != nil { - return fmt.Errorf("Error flattening `profile` of Autoscale Setting %q (Resource Group %q): %+v", name, resourceGroup, err) - } - if err = d.Set("profile", profile); err != nil { - return fmt.Errorf("Error setting `profile` of Autoscale Setting %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - notifications := flattenAzureRmAutoScaleSettingNotification(resp.Notifications) - if err = d.Set("notification", notifications); err != nil { - return fmt.Errorf("Error setting `notification` of Autoscale Setting %q (resource group %q): %+v", name, resourceGroup, err) - } - - // Return a new tag map filtered by the specified tag names. - tagMap := tags.Filter(resp.Tags, "$type") - return tags.FlattenAndSet(d, tagMap) -} - -func resourceArmAutoScaleSettingDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AutoscaleSettingsClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["autoscalesettings"] - - resp, err := client.Delete(ctx, resourceGroup, name) - if err != nil { - if !response.WasNotFound(resp.Response) { - return fmt.Errorf("Error deleting AutoScale Setting %q (Resource Group %q): %+v", name, resourceGroup, err) - } - } - - return nil -} - -func expandAzureRmAutoScaleSettingProfile(input []interface{}) (*[]insights.AutoscaleProfile, error) { - results := make([]insights.AutoscaleProfile, 0) - - for _, v := range input { - raw := v.(map[string]interface{}) - - name := raw["name"].(string) - - // this is Required, so we don't need to check for optionals here - capacitiesRaw := raw["capacity"].([]interface{}) - capacityRaw := capacitiesRaw[0].(map[string]interface{}) - capacity := insights.ScaleCapacity{ - Minimum: utils.String(strconv.Itoa(capacityRaw["minimum"].(int))), - Maximum: utils.String(strconv.Itoa(capacityRaw["maximum"].(int))), - Default: utils.String(strconv.Itoa(capacityRaw["default"].(int))), - } - - recurrencesRaw := raw["recurrence"].([]interface{}) - recurrence := expandAzureRmAutoScaleSettingRecurrence(recurrencesRaw) - - rulesRaw := raw["rule"].([]interface{}) - rules := expandAzureRmAutoScaleSettingRule(rulesRaw) - - fixedDatesRaw := raw["fixed_date"].([]interface{}) - fixedDate, err := expandAzureRmAutoScaleSettingFixedDate(fixedDatesRaw) - if err != nil { - return nil, fmt.Errorf("Error expanding `fixed_date`: %+v", err) - } - - result := insights.AutoscaleProfile{ - Name: utils.String(name), - Capacity: &capacity, - FixedDate: fixedDate, - Recurrence: recurrence, - Rules: rules, - } - results = append(results, result) - } - - return &results, nil -} - -func expandAzureRmAutoScaleSettingRule(input []interface{}) *[]insights.ScaleRule { - rules := make([]insights.ScaleRule, 0) - - for _, v := range input { - ruleRaw := v.(map[string]interface{}) - - triggersRaw := ruleRaw["metric_trigger"].([]interface{}) - triggerRaw := triggersRaw[0].(map[string]interface{}) - metricTrigger := insights.MetricTrigger{ - MetricName: utils.String(triggerRaw["metric_name"].(string)), - MetricResourceURI: utils.String(triggerRaw["metric_resource_id"].(string)), - TimeGrain: utils.String(triggerRaw["time_grain"].(string)), - Statistic: insights.MetricStatisticType(triggerRaw["statistic"].(string)), - TimeWindow: utils.String(triggerRaw["time_window"].(string)), - TimeAggregation: insights.TimeAggregationType(triggerRaw["time_aggregation"].(string)), - Operator: insights.ComparisonOperationType(triggerRaw["operator"].(string)), - Threshold: utils.Float(triggerRaw["threshold"].(float64)), - } - - actionsRaw := ruleRaw["scale_action"].([]interface{}) - actionRaw := actionsRaw[0].(map[string]interface{}) - scaleAction := insights.ScaleAction{ - Direction: insights.ScaleDirection(actionRaw["direction"].(string)), - Type: insights.ScaleType(actionRaw["type"].(string)), - Value: utils.String(strconv.Itoa(actionRaw["value"].(int))), - Cooldown: utils.String(actionRaw["cooldown"].(string)), - } - - rule := insights.ScaleRule{ - MetricTrigger: &metricTrigger, - ScaleAction: &scaleAction, - } - - rules = append(rules, rule) - } - - return &rules -} - -func expandAzureRmAutoScaleSettingFixedDate(input []interface{}) (*insights.TimeWindow, error) { - if len(input) == 0 { - return nil, nil - } - - raw := input[0].(map[string]interface{}) - - startString := raw["start"].(string) - startTime, err := date.ParseTime(time.RFC3339, startString) - if err != nil { - return nil, fmt.Errorf("Failed to parse `start` time %q as an RFC3339 date: %+v", startString, err) - } - endString := raw["end"].(string) - endTime, err := date.ParseTime(time.RFC3339, endString) - if err != nil { - return nil, fmt.Errorf("Failed to parse `end` time %q as an RFC3339 date: %+v", endString, err) - } - - timeZone := raw["timezone"].(string) - timeWindow := insights.TimeWindow{ - TimeZone: utils.String(timeZone), - Start: &date.Time{ - Time: startTime, - }, - End: &date.Time{ - Time: endTime, - }, - } - return &timeWindow, nil -} - -func expandAzureRmAutoScaleSettingRecurrence(input []interface{}) *insights.Recurrence { - if len(input) == 0 { - return nil - } - - recurrenceRaw := input[0].(map[string]interface{}) - - timeZone := recurrenceRaw["timezone"].(string) - days := make([]string, 0) - for _, dayItem := range recurrenceRaw["days"].([]interface{}) { - days = append(days, dayItem.(string)) - } - - hours := make([]int32, 0) - for _, hourItem := range recurrenceRaw["hours"].([]interface{}) { - hours = append(hours, int32(hourItem.(int))) - } - - minutes := make([]int32, 0) - for _, minuteItem := range recurrenceRaw["minutes"].([]interface{}) { - minutes = append(minutes, int32(minuteItem.(int))) - } - - return &insights.Recurrence{ - // API docs say this has to be `Week`. - Frequency: insights.RecurrenceFrequencyWeek, - Schedule: &insights.RecurrentSchedule{ - TimeZone: utils.String(timeZone), - Days: &days, - Hours: &hours, - Minutes: &minutes, - }, - } -} - -func expandAzureRmAutoScaleSettingNotifications(input []interface{}) *[]insights.AutoscaleNotification { - notifications := make([]insights.AutoscaleNotification, 0) - - for _, v := range input { - notificationRaw := v.(map[string]interface{}) - - emailsRaw := notificationRaw["email"].([]interface{}) - emailRaw := emailsRaw[0].(map[string]interface{}) - email := expandAzureRmAutoScaleSettingNotificationEmail(emailRaw) - - configsRaw := notificationRaw["webhook"].([]interface{}) - webhooks := expandAzureRmAutoScaleSettingNotificationWebhook(configsRaw) - - notification := insights.AutoscaleNotification{ - Email: email, - Operation: utils.String("scale"), - Webhooks: webhooks, - } - notifications = append(notifications, notification) - } - - return ¬ifications -} - -func expandAzureRmAutoScaleSettingNotificationEmail(input map[string]interface{}) *insights.EmailNotification { - customEmails := make([]string, 0) - if v, ok := input["custom_emails"]; ok { - for _, item := range v.([]interface{}) { - customEmails = append(customEmails, item.(string)) - } - } - - email := insights.EmailNotification{ - CustomEmails: &customEmails, - SendToSubscriptionAdministrator: utils.Bool(input["send_to_subscription_administrator"].(bool)), - SendToSubscriptionCoAdministrators: utils.Bool(input["send_to_subscription_co_administrator"].(bool)), - } - - return &email -} - -func expandAzureRmAutoScaleSettingNotificationWebhook(input []interface{}) *[]insights.WebhookNotification { - webhooks := make([]insights.WebhookNotification, 0) - - for _, v := range input { - webhookRaw := v.(map[string]interface{}) - - webhook := insights.WebhookNotification{ - ServiceURI: utils.String(webhookRaw["service_uri"].(string)), - } - - if props, ok := webhookRaw["properties"]; ok { - properties := make(map[string]*string) - for key, value := range props.(map[string]interface{}) { - properties[key] = utils.String(value.(string)) - } - - webhook.Properties = properties - } - - webhooks = append(webhooks, webhook) - } - - return &webhooks -} - -func flattenAzureRmAutoScaleSettingProfile(profiles *[]insights.AutoscaleProfile) ([]interface{}, error) { - if profiles == nil { - return []interface{}{}, nil - } - - results := make([]interface{}, 0) - for _, profile := range *profiles { - result := make(map[string]interface{}) - - if name := profile.Name; name != nil { - result["name"] = *name - } - - capacity, err := flattenAzureRmAutoScaleSettingCapacity(profile.Capacity) - if err != nil { - return nil, fmt.Errorf("Error flattening `capacity`: %+v", err) - } - result["capacity"] = capacity - - result["fixed_date"] = flattenAzureRmAutoScaleSettingFixedDate(profile.FixedDate) - result["recurrence"] = flattenAzureRmAutoScaleSettingRecurrence(profile.Recurrence) - - rule, err := flattenAzureRmAutoScaleSettingRules(profile.Rules) - if err != nil { - return nil, fmt.Errorf("Error flattening Rule: %s", err) - } - result["rule"] = rule - - results = append(results, result) - } - return results, nil -} - -func flattenAzureRmAutoScaleSettingCapacity(input *insights.ScaleCapacity) ([]interface{}, error) { - if input == nil { - return []interface{}{}, nil - } - - result := make(map[string]interface{}) - - if minStr := input.Minimum; minStr != nil { - min, err := strconv.Atoi(*minStr) - if err != nil { - return nil, fmt.Errorf("Error converting Minimum Scale Capacity %q to an int: %+v", *minStr, err) - } - result["minimum"] = min - } - - if maxStr := input.Maximum; maxStr != nil { - max, err := strconv.Atoi(*maxStr) - if err != nil { - return nil, fmt.Errorf("Error converting Maximum Scale Capacity %q to an int: %+v", *maxStr, err) - } - result["maximum"] = max - } - - if defaultCapacityStr := input.Default; defaultCapacityStr != nil { - defaultCapacity, err := strconv.Atoi(*defaultCapacityStr) - if err != nil { - return nil, fmt.Errorf("Error converting Default Scale Capacity %q to an int: %+v", *defaultCapacityStr, err) - } - result["default"] = defaultCapacity - } - - return []interface{}{result}, nil -} - -func flattenAzureRmAutoScaleSettingRules(input *[]insights.ScaleRule) ([]interface{}, error) { - if input == nil { - return []interface{}{}, nil - } - - results := make([]interface{}, 0) - for _, rule := range *input { - result := make(map[string]interface{}) - - metricTriggers := make([]interface{}, 0) - if trigger := rule.MetricTrigger; trigger != nil { - output := make(map[string]interface{}) - - output["operator"] = string(trigger.Operator) - output["statistic"] = string(trigger.Statistic) - output["time_aggregation"] = string(trigger.TimeAggregation) - - if trigger.MetricName != nil { - output["metric_name"] = *trigger.MetricName - } - - if trigger.MetricResourceURI != nil { - output["metric_resource_id"] = *trigger.MetricResourceURI - } - - if trigger.TimeGrain != nil { - output["time_grain"] = *trigger.TimeGrain - } - - if trigger.TimeWindow != nil { - output["time_window"] = *trigger.TimeWindow - } - - if trigger.Threshold != nil { - output["threshold"] = *trigger.Threshold - } - - metricTriggers = append(metricTriggers, output) - } - - result["metric_trigger"] = metricTriggers - - scaleActions := make([]interface{}, 0) - if v := rule.ScaleAction; v != nil { - action := make(map[string]interface{}) - - action["direction"] = string(v.Direction) - action["type"] = string(v.Type) - - if v.Cooldown != nil { - action["cooldown"] = *v.Cooldown - } - - if val := v.Value; val != nil && *val != "" { - i, err := strconv.Atoi(*val) - if err != nil { - return nil, fmt.Errorf("`value` %q was not convertable to an int: %s", *val, err) - } - action["value"] = i - } - - scaleActions = append(scaleActions, action) - } - - result["scale_action"] = scaleActions - - results = append(results, result) - } - - return results, nil -} - -func flattenAzureRmAutoScaleSettingFixedDate(input *insights.TimeWindow) []interface{} { - if input == nil { - return []interface{}{} - } - - result := make(map[string]interface{}) - - if timezone := input.TimeZone; timezone != nil { - result["timezone"] = *timezone - } - - if start := input.Start; start != nil { - result["start"] = start.String() - } - - if end := input.End; end != nil { - result["end"] = end.String() - } - - return []interface{}{result} -} - -func flattenAzureRmAutoScaleSettingRecurrence(input *insights.Recurrence) []interface{} { - if input == nil { - return []interface{}{} - } - - result := make(map[string]interface{}) - - if schedule := input.Schedule; schedule != nil { - if timezone := schedule.TimeZone; timezone != nil { - result["timezone"] = *timezone - } - - days := make([]string, 0) - if s := schedule.Days; s != nil { - days = *s - } - result["days"] = days - - hours := make([]int, 0) - if schedule.Hours != nil { - for _, v := range *schedule.Hours { - hours = append(hours, int(v)) - } - } - result["hours"] = hours - - minutes := make([]int, 0) - if schedule.Minutes != nil { - for _, v := range *schedule.Minutes { - minutes = append(minutes, int(v)) - } - } - result["minutes"] = minutes - } - - return []interface{}{result} -} - -func flattenAzureRmAutoScaleSettingNotification(notifications *[]insights.AutoscaleNotification) []interface{} { - results := make([]interface{}, 0) - - if notifications == nil { - return results - } - - for _, notification := range *notifications { - result := make(map[string]interface{}) - - emails := make([]interface{}, 0) - if email := notification.Email; email != nil { - block := make(map[string]interface{}) - - if send := email.SendToSubscriptionAdministrator; send != nil { - block["send_to_subscription_administrator"] = *send - } - - if send := email.SendToSubscriptionCoAdministrators; send != nil { - block["send_to_subscription_co_administrator"] = *send - } - - customEmails := make([]interface{}, 0) - if custom := email.CustomEmails; custom != nil { - for _, v := range *custom { - customEmails = append(customEmails, v) - } - } - block["custom_emails"] = customEmails - - emails = append(emails, block) - } - result["email"] = emails - - webhooks := make([]interface{}, 0) - if hooks := notification.Webhooks; hooks != nil { - for _, v := range *hooks { - hook := make(map[string]interface{}) - - if v.ServiceURI != nil { - hook["service_uri"] = *v.ServiceURI - } - - props := make(map[string]string) - for key, value := range v.Properties { - if value != nil { - props[key] = *value - } - } - hook["properties"] = props - webhooks = append(webhooks, hook) - } - } - - result["webhook"] = webhooks - - results = append(results, result) - } - return results -} - -func validateAutoScaleSettingsTimeZone() schema.SchemaValidateFunc { - // from https://docs.microsoft.com/en-us/rest/api/monitor/autoscalesettings/createorupdate#timewindow - timeZones := []string{ - "Dateline Standard Time", - "UTC-11", - "Hawaiian Standard Time", - "Alaskan Standard Time", - "Pacific Standard Time (Mexico)", - "Pacific Standard Time", - "US Mountain Standard Time", - "Mountain Standard Time (Mexico)", - "Mountain Standard Time", - "Central America Standard Time", - "Central Standard Time", - "Central Standard Time (Mexico)", - "Canada Central Standard Time", - "SA Pacific Standard Time", - "Eastern Standard Time", - "US Eastern Standard Time", - "Venezuela Standard Time", - "Paraguay Standard Time", - "Atlantic Standard Time", - "Central Brazilian Standard Time", - "SA Western Standard Time", - "Pacific SA Standard Time", - "Newfoundland Standard Time", - "E. South America Standard Time", - "Argentina Standard Time", - "SA Eastern Standard Time", - "Greenland Standard Time", - "Montevideo Standard Time", - "Bahia Standard Time", - "UTC-02", - "Mid-Atlantic Standard Time", - "Azores Standard Time", - "Cape Verde Standard Time", - "Morocco Standard Time", - "UTC", - "GMT Standard Time", - "Greenwich Standard Time", - "W. Europe Standard Time", - "Central Europe Standard Time", - "Romance Standard Time", - "Central European Standard Time", - "W. Central Africa Standard Time", - "Namibia Standard Time", - "Jordan Standard Time", - "GTB Standard Time", - "Middle East Standard Time", - "Egypt Standard Time", - "Syria Standard Time", - "E. Europe Standard Time", - "South Africa Standard Time", - "FLE Standard Time", - "Turkey Standard Time", - "Israel Standard Time", - "Kaliningrad Standard Time", - "Libya Standard Time", - "Arabic Standard Time", - "Arab Standard Time", - "Belarus Standard Time", - "Russian Standard Time", - "E. Africa Standard Time", - "Iran Standard Time", - "Arabian Standard Time", - "Azerbaijan Standard Time", - "Russia Time Zone 3", - "Mauritius Standard Time", - "Georgian Standard Time", - "Caucasus Standard Time", - "Afghanistan Standard Time", - "West Asia Standard Time", - "Ekaterinburg Standard Time", - "Pakistan Standard Time", - "India Standard Time", - "Sri Lanka Standard Time", - "Nepal Standard Time", - "Central Asia Standard Time", - "Bangladesh Standard Time", - "N. Central Asia Standard Time", - "Myanmar Standard Time", - "SE Asia Standard Time", - "North Asia Standard Time", - "China Standard Time", - "North Asia East Standard Time", - "Singapore Standard Time", - "W. Australia Standard Time", - "Taipei Standard Time", - "Ulaanbaatar Standard Time", - "Tokyo Standard Time", - "Korea Standard Time", - "Yakutsk Standard Time", - "Cen. Australia Standard Time", - "AUS Central Standard Time", - "E. Australia Standard Time", - "AUS Eastern Standard Time", - "West Pacific Standard Time", - "Tasmania Standard Time", - "Magadan Standard Time", - "Vladivostok Standard Time", - "Russia Time Zone 10", - "Central Pacific Standard Time", - "Russia Time Zone 11", - "New Zealand Standard Time", - "UTC+12", - "Fiji Standard Time", - "Kamchatka Standard Time", - "Tonga Standard Time", - "Samoa Standard Time", - "Line Islands Standard Time", - } - return validation.StringInSlice(timeZones, false) -} diff --git a/azurerm/internal/services/monitor/resource_arm_metric_alertrule.go b/azurerm/internal/services/monitor/resource_arm_metric_alertrule.go deleted file mode 100644 index dba743c5cbdc..000000000000 --- a/azurerm/internal/services/monitor/resource_arm_metric_alertrule.go +++ /dev/null @@ -1,476 +0,0 @@ -package monitor - -import ( - "fmt" - "log" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmMetricAlertRule() *schema.Resource { - return &schema.Resource{ - Create: resourceArmMetricAlertRuleCreateUpdate, - Read: resourceArmMetricAlertRuleRead, - Update: resourceArmMetricAlertRuleCreateUpdate, - Delete: resourceArmMetricAlertRuleDelete, - - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - DeprecationMessage: `The 'azurerm_metric_alertrule' resource is deprecated in favour of the renamed version 'azurerm_monitor_metric_alertrule'. - -Information on migrating to the renamed resource can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-between-renamed-resources.html - -As such the existing 'azurerm_metric_alertrule' resource is deprecated and will be removed in the next major version of the AzureRM Provider (2.0). -`, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "resource_group_name": azure.SchemaResourceGroupName(), - - "location": azure.SchemaLocation(), - - "description": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - - "resource_id": { - Type: schema.TypeString, - Required: true, - }, - - "metric_name": { - Type: schema.TypeString, - Required: true, - }, - - "operator": { - Type: schema.TypeString, - Required: true, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.ConditionOperatorGreaterThan), - string(insights.ConditionOperatorGreaterThanOrEqual), - string(insights.ConditionOperatorLessThan), - string(insights.ConditionOperatorLessThanOrEqual), - }, true), - }, - - "threshold": { - Type: schema.TypeFloat, - Required: true, - }, - - "period": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.ISO8601Duration, - }, - - "aggregation": { - Type: schema.TypeString, - Required: true, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.TimeAggregationOperatorAverage), - string(insights.TimeAggregationOperatorLast), - string(insights.TimeAggregationOperatorMaximum), - string(insights.TimeAggregationOperatorMinimum), - string(insights.TimeAggregationOperatorTotal), - }, true), - }, - - "email_action": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "send_to_service_owners": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - }, - - "custom_emails": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - - "webhook_action": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "service_uri": { - Type: schema.TypeString, - Required: true, - }, - - "properties": { - Type: schema.TypeMap, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - - "tags": { - Type: schema.TypeMap, - Optional: true, - Computed: true, - ValidateFunc: ValidateMetricAlertRuleTags, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - } -} - -func resourceArmMetricAlertRuleCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AlertRulesClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - log.Printf("[INFO] preparing arguments for AzureRM Alert Rule creation.") - - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing Alert Rule %q (Resource Group %q): %s", name, resourceGroup, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_metric_alertrule", *existing.ID) - } - } - - location := azure.NormalizeLocation(d.Get("location").(string)) - t := d.Get("tags").(map[string]interface{}) - - alertRule, err := expandAzureRmMetricThresholdAlertRule(d) - if err != nil { - return err - } - - alertRuleResource := insights.AlertRuleResource{ - Name: &name, - Location: &location, - Tags: tags.Expand(t), - AlertRule: alertRule, - } - - if _, err = client.CreateOrUpdate(ctx, resourceGroup, name, alertRuleResource); err != nil { - return err - } - - read, err := client.Get(ctx, resourceGroup, name) - if err != nil { - return err - } - if read.ID == nil { - return fmt.Errorf("Cannot read AzureRM Alert Rule %q (Resource Group %s) ID", name, resourceGroup) - } - - d.SetId(*read.ID) - - return resourceArmMetricAlertRuleRead(d, meta) -} - -func resourceArmMetricAlertRuleRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AlertRulesClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resourceGroup, name, err := resourceGroupAndAlertRuleNameFromId(d.Id()) - if err != nil { - return err - } - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Metric Alert Rule %q (resource group %q) was not found - removing from state", name, resourceGroup) - d.SetId("") - return nil - } - - return fmt.Errorf("Error making Read request on AzureRM Metric Alert Rule %q: %+v", name, err) - } - - d.Set("name", name) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - if alertRule := resp.AlertRule; alertRule != nil { - d.Set("description", alertRule.Description) - d.Set("enabled", alertRule.IsEnabled) - - ruleCondition := alertRule.Condition - - if ruleCondition != nil { - if thresholdRuleCondition, ok := ruleCondition.AsThresholdRuleCondition(); ok && thresholdRuleCondition != nil { - d.Set("operator", string(thresholdRuleCondition.Operator)) - d.Set("threshold", thresholdRuleCondition.Threshold) - d.Set("period", thresholdRuleCondition.WindowSize) - d.Set("aggregation", string(thresholdRuleCondition.TimeAggregation)) - - dataSource := thresholdRuleCondition.DataSource - - if dataSource != nil { - if metricDataSource, ok := dataSource.AsRuleMetricDataSource(); ok && metricDataSource != nil { - d.Set("resource_id", metricDataSource.ResourceURI) - d.Set("metric_name", metricDataSource.MetricName) - } - } - } - } - - email_actions := make([]interface{}, 0) - webhook_actions := make([]interface{}, 0) - - for _, ruleAction := range *alertRule.Actions { - if emailAction, ok := ruleAction.AsRuleEmailAction(); ok && emailAction != nil { - email_action := make(map[string]interface{}, 1) - - if sendToOwners := emailAction.SendToServiceOwners; sendToOwners != nil { - email_action["send_to_service_owners"] = *sendToOwners - } - - custom_emails := make([]string, 0) - if s := emailAction.CustomEmails; s != nil { - custom_emails = *s - } - email_action["custom_emails"] = custom_emails - - email_actions = append(email_actions, email_action) - } else if webhookAction, ok := ruleAction.AsRuleWebhookAction(); ok && webhookAction != nil { - webhook_action := make(map[string]interface{}, 1) - - webhook_action["service_uri"] = *webhookAction.ServiceURI - - properties := make(map[string]string) - for k, v := range webhookAction.Properties { - if k != "$type" { - if v != nil { - properties[k] = *v - } - } - } - webhook_action["properties"] = properties - - webhook_actions = append(webhook_actions, webhook_action) - } - } - - d.Set("email_action", email_actions) - d.Set("webhook_action", webhook_actions) - } - - // Return a new tag map filtered by the specified tag names. - tagMap := tags.Filter(resp.Tags, "$type") - - return tags.FlattenAndSet(d, tagMap) -} - -func resourceArmMetricAlertRuleDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AlertRulesClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - resourceGroup, name, err := resourceGroupAndAlertRuleNameFromId(d.Id()) - if err != nil { - return err - } - - resp, err := client.Delete(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp) { - return nil - } - - return fmt.Errorf("Error deleting Metric Alert Rule %q (resource group %q): %+v", name, resourceGroup, err) - } - - return err -} - -func expandAzureRmMetricThresholdAlertRule(d *schema.ResourceData) (*insights.AlertRule, error) { - name := d.Get("name").(string) - - resource := d.Get("resource_id").(string) - metric_name := d.Get("metric_name").(string) - - metricDataSource := insights.RuleMetricDataSource{ - ResourceURI: &resource, - MetricName: &metric_name, - } - - operator := d.Get("operator").(string) - threshold := d.Get("threshold").(float64) - period := d.Get("period").(string) - aggregation := d.Get("aggregation").(string) - - thresholdRuleCondition := insights.ThresholdRuleCondition{ - DataSource: metricDataSource, - Operator: insights.ConditionOperator(operator), - Threshold: &threshold, - TimeAggregation: insights.TimeAggregationOperator(aggregation), - WindowSize: &period, - } - - actions := make([]insights.BasicRuleAction, 0, 2) - - // Email action - - email_actions := d.Get("email_action").([]interface{}) - - if len(email_actions) > 0 { - email_action := email_actions[0].(map[string]interface{}) - emailAction := insights.RuleEmailAction{} - - if v, ok := email_action["custom_emails"]; ok { - custom_emails := v.([]interface{}) - - customEmails := make([]string, 0) - for _, customEmail := range custom_emails { - custom_email := customEmail.(string) - customEmails = append(customEmails, custom_email) - } - - emailAction.CustomEmails = &customEmails - } - - if v, ok := email_action["send_to_service_owners"]; ok { - sendToServiceOwners := v.(bool) - emailAction.SendToServiceOwners = &sendToServiceOwners - } - - actions = append(actions, emailAction) - } - - // Webhook action - - webhook_actions := d.Get("webhook_action").([]interface{}) - - if len(webhook_actions) > 0 { - webhook_action := webhook_actions[0].(map[string]interface{}) - - service_uri := webhook_action["service_uri"].(string) - - webhook_properties := make(map[string]*string) - - if v, ok := webhook_action["properties"]; ok { - properties := v.(map[string]interface{}) - - for property_key, property_value := range properties { - property_string := property_value.(string) - webhook_properties[property_key] = &property_string - } - } - - webhookAction := insights.RuleWebhookAction{ - ServiceURI: &service_uri, - Properties: webhook_properties, - } - - actions = append(actions, webhookAction) - } - - enabled := d.Get("enabled").(bool) - - alertRule := insights.AlertRule{ - Name: &name, - Condition: &thresholdRuleCondition, - Actions: &actions, - IsEnabled: &enabled, - } - - if v, ok := d.GetOk("description"); ok { - description := v.(string) - alertRule.Description = &description - } - - return &alertRule, nil -} - -func ValidateMetricAlertRuleTags(v interface{}, f string) (warnings []string, errors []error) { - // Normal validation required by any AzureRM resource. - warnings, errors = tags.Validate(v, f) - - tagsMap := v.(map[string]interface{}) - - for k := range tagsMap { - if strings.EqualFold(k, "$type") { - errors = append(errors, fmt.Errorf("the %q is not allowed as tag name", k)) - } - } - - return warnings, errors -} - -func resourceGroupAndAlertRuleNameFromId(alertRuleId string) (string, string, error) { - id, err := azure.ParseAzureResourceID(alertRuleId) - if err != nil { - return "", "", err - } - name := id.Path["alertrules"] - resourceGroup := id.ResourceGroup - - return resourceGroup, name, nil -} diff --git a/azurerm/internal/services/monitor/resource_arm_monitor_metric_alertrule.go b/azurerm/internal/services/monitor/resource_arm_monitor_metric_alertrule.go deleted file mode 100644 index efbaae8559d5..000000000000 --- a/azurerm/internal/services/monitor/resource_arm_monitor_metric_alertrule.go +++ /dev/null @@ -1,462 +0,0 @@ -package monitor - -import ( - "fmt" - "log" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmMonitorMetricAlertRule() *schema.Resource { - return &schema.Resource{ - Create: resourceArmMonitorMetricAlertRuleCreateUpdate, - Read: resourceArmMonitorMetricAlertRuleRead, - Update: resourceArmMonitorMetricAlertRuleCreateUpdate, - Delete: resourceArmMonitorMetricAlertRuleDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "resource_group_name": azure.SchemaResourceGroupName(), - - "location": azure.SchemaLocation(), - - "description": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - - "resource_id": { - Type: schema.TypeString, - Required: true, - }, - - "metric_name": { - Type: schema.TypeString, - Required: true, - }, - - "operator": { - Type: schema.TypeString, - Required: true, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.ConditionOperatorGreaterThan), - string(insights.ConditionOperatorGreaterThanOrEqual), - string(insights.ConditionOperatorLessThan), - string(insights.ConditionOperatorLessThanOrEqual), - }, true), - }, - - "threshold": { - Type: schema.TypeFloat, - Required: true, - }, - - "period": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.ISO8601Duration, - }, - - "aggregation": { - Type: schema.TypeString, - Required: true, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(insights.TimeAggregationOperatorAverage), - string(insights.TimeAggregationOperatorLast), - string(insights.TimeAggregationOperatorMaximum), - string(insights.TimeAggregationOperatorMinimum), - string(insights.TimeAggregationOperatorTotal), - }, true), - }, - - "email_action": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "send_to_service_owners": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - }, - - "custom_emails": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - - "webhook_action": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "service_uri": { - Type: schema.TypeString, - Required: true, - }, - - "properties": { - Type: schema.TypeMap, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - - "tags": { - Type: schema.TypeMap, - Optional: true, - Computed: true, - ValidateFunc: ValidateMetricAlertRuleTags, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - } -} - -func resourceArmMonitorMetricAlertRuleCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AlertRulesClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - log.Printf("[INFO] preparing arguments for AzureRM Alert Rule creation.") - - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing Alert Rule %q (Resource Group %q): %s", name, resourceGroup, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_monitor_metric_alertrule", *existing.ID) - } - } - - location := azure.NormalizeLocation(d.Get("location").(string)) - t := d.Get("tags").(map[string]interface{}) - - alertRule, err := expandAzureRmMonitorMetricThresholdAlertRule(d) - if err != nil { - return err - } - - alertRuleResource := insights.AlertRuleResource{ - Name: &name, - Location: &location, - Tags: tags.Expand(t), - AlertRule: alertRule, - } - - if _, err = client.CreateOrUpdate(ctx, resourceGroup, name, alertRuleResource); err != nil { - return err - } - - read, err := client.Get(ctx, resourceGroup, name) - if err != nil { - return err - } - if read.ID == nil { - return fmt.Errorf("Cannot read AzureRM Alert Rule %q (Resource Group %s) ID", name, resourceGroup) - } - - d.SetId(*read.ID) - - return resourceArmMonitorMetricAlertRuleRead(d, meta) -} - -func resourceArmMonitorMetricAlertRuleRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AlertRulesClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - name := id.Path["alertrules"] - resourceGroup := id.ResourceGroup - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Metric Alert Rule %q (resource group %q) was not found - removing from state", name, resourceGroup) - d.SetId("") - return nil - } - - return fmt.Errorf("Error making Read request on AzureRM Metric Alert Rule %q: %+v", name, err) - } - - d.Set("name", name) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - if alertRule := resp.AlertRule; alertRule != nil { - d.Set("description", alertRule.Description) - d.Set("enabled", alertRule.IsEnabled) - - ruleCondition := alertRule.Condition - - if ruleCondition != nil { - if thresholdRuleCondition, ok := ruleCondition.AsThresholdRuleCondition(); ok && thresholdRuleCondition != nil { - d.Set("operator", string(thresholdRuleCondition.Operator)) - d.Set("threshold", thresholdRuleCondition.Threshold) - d.Set("period", thresholdRuleCondition.WindowSize) - d.Set("aggregation", string(thresholdRuleCondition.TimeAggregation)) - - dataSource := thresholdRuleCondition.DataSource - - if dataSource != nil { - if metricDataSource, ok := dataSource.AsRuleMetricDataSource(); ok && metricDataSource != nil { - d.Set("resource_id", metricDataSource.ResourceURI) - d.Set("metric_name", metricDataSource.MetricName) - } - } - } - } - - email_actions := make([]interface{}, 0) - webhook_actions := make([]interface{}, 0) - - for _, ruleAction := range *alertRule.Actions { - if emailAction, ok := ruleAction.AsRuleEmailAction(); ok && emailAction != nil { - email_action := make(map[string]interface{}, 1) - - if sendToOwners := emailAction.SendToServiceOwners; sendToOwners != nil { - email_action["send_to_service_owners"] = *sendToOwners - } - - custom_emails := make([]string, 0) - if s := emailAction.CustomEmails; s != nil { - custom_emails = *s - } - email_action["custom_emails"] = custom_emails - - email_actions = append(email_actions, email_action) - } else if webhookAction, ok := ruleAction.AsRuleWebhookAction(); ok && webhookAction != nil { - webhook_action := make(map[string]interface{}, 1) - - webhook_action["service_uri"] = *webhookAction.ServiceURI - - properties := make(map[string]string) - for k, v := range webhookAction.Properties { - if k != "$type" { - if v != nil { - properties[k] = *v - } - } - } - webhook_action["properties"] = properties - - webhook_actions = append(webhook_actions, webhook_action) - } - } - - d.Set("email_action", email_actions) - d.Set("webhook_action", webhook_actions) - } - - // Return a new tag map filtered by the specified tag names. - tagMap := tags.Filter(resp.Tags, "$type") - - return tags.FlattenAndSet(d, tagMap) -} - -func resourceArmMonitorMetricAlertRuleDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Monitor.AlertRulesClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - name := id.Path["alertrules"] - resourceGroup := id.ResourceGroup - - resp, err := client.Delete(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp) { - return nil - } - - return fmt.Errorf("Error deleting Metric Alert Rule %q (resource group %q): %+v", name, resourceGroup, err) - } - - return err -} - -func expandAzureRmMonitorMetricThresholdAlertRule(d *schema.ResourceData) (*insights.AlertRule, error) { - name := d.Get("name").(string) - - resource := d.Get("resource_id").(string) - metric_name := d.Get("metric_name").(string) - - metricDataSource := insights.RuleMetricDataSource{ - ResourceURI: &resource, - MetricName: &metric_name, - } - - operator := d.Get("operator").(string) - threshold := d.Get("threshold").(float64) - period := d.Get("period").(string) - aggregation := d.Get("aggregation").(string) - - thresholdRuleCondition := insights.ThresholdRuleCondition{ - DataSource: metricDataSource, - Operator: insights.ConditionOperator(operator), - Threshold: &threshold, - TimeAggregation: insights.TimeAggregationOperator(aggregation), - WindowSize: &period, - } - - actions := make([]insights.BasicRuleAction, 0, 2) - - // Email action - - email_actions := d.Get("email_action").([]interface{}) - - if len(email_actions) > 0 { - email_action := email_actions[0].(map[string]interface{}) - emailAction := insights.RuleEmailAction{} - - if v, ok := email_action["custom_emails"]; ok { - custom_emails := v.([]interface{}) - - customEmails := make([]string, 0) - for _, customEmail := range custom_emails { - custom_email := customEmail.(string) - customEmails = append(customEmails, custom_email) - } - - emailAction.CustomEmails = &customEmails - } - - if v, ok := email_action["send_to_service_owners"]; ok { - sendToServiceOwners := v.(bool) - emailAction.SendToServiceOwners = &sendToServiceOwners - } - - actions = append(actions, emailAction) - } - - // Webhook action - - webhook_actions := d.Get("webhook_action").([]interface{}) - - if len(webhook_actions) > 0 { - webhook_action := webhook_actions[0].(map[string]interface{}) - - service_uri := webhook_action["service_uri"].(string) - - webhook_properties := make(map[string]*string) - - if v, ok := webhook_action["properties"]; ok { - properties := v.(map[string]interface{}) - - for property_key, property_value := range properties { - property_string := property_value.(string) - webhook_properties[property_key] = &property_string - } - } - - webhookAction := insights.RuleWebhookAction{ - ServiceURI: &service_uri, - Properties: webhook_properties, - } - - actions = append(actions, webhookAction) - } - - enabled := d.Get("enabled").(bool) - - alertRule := insights.AlertRule{ - Name: &name, - Condition: &thresholdRuleCondition, - Actions: &actions, - IsEnabled: &enabled, - } - - if v, ok := d.GetOk("description"); ok { - description := v.(string) - alertRule.Description = &description - } - - return &alertRule, nil -} - -func ValidateMonitorMetricAlertRuleTags(v interface{}, f string) (warnings []string, errors []error) { - // Normal validation required by any AzureRM resource. - warnings, errors = tags.Validate(v, f) - - tagsMap := v.(map[string]interface{}) - - for k := range tagsMap { - if strings.EqualFold(k, "$type") { - errors = append(errors, fmt.Errorf("the %q is not allowed as tag name", k)) - } - } - - return warnings, errors -} diff --git a/azurerm/internal/services/monitor/tests/resource_arm_autoscale_setting_test.go b/azurerm/internal/services/monitor/tests/resource_arm_autoscale_setting_test.go deleted file mode 100644 index ce680d4a64a4..000000000000 --- a/azurerm/internal/services/monitor/tests/resource_arm_autoscale_setting_test.go +++ /dev/null @@ -1,918 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" -) - -func TestAccAzureRMAutoScaleSetting_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.name", "metricRules"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.rule.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "0"), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMAutoScaleSetting_requiresImport(data), - ExpectError: acceptance.RequiresImportError("azurerm_autoscale_setting"), - }, - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_multipleProfiles(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_multipleProfiles(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "2"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.name", "primary"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.1.name", "secondary"), - ), - }, - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_update(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_capacity(data, 1, 3, 2), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "false"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.minimum", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.maximum", "3"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.default", "2"), - ), - }, - { - Config: testAccAzureRMAutoScaleSetting_capacity(data, 0, 400, 0), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "false"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.minimum", "0"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.maximum", "400"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.default", "0"), - ), - }, - { - Config: testAccAzureRMAutoScaleSetting_capacity(data, 2, 45, 3), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "false"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.minimum", "2"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.maximum", "45"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.capacity.0.default", "3"), - ), - }, - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_multipleRules(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.name", "metricRules"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.rule.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.rule.0.scale_action.0.direction", "Increase"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "0"), - ), - }, - { - Config: testAccAzureRMAutoScaleSetting_multipleRules(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.name", "metricRules"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.rule.#", "2"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.rule.0.scale_action.0.direction", "Increase"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.rule.1.scale_action.0.direction", "Decrease"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "0"), - ), - }, - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_customEmails(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_email(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.0.custom_emails.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.0.custom_emails.0", fmt.Sprintf("acctest1-%d@example.com", data.RandomInteger)), - ), - }, - { - Config: testAccAzureRMAutoScaleSetting_emailUpdated(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.0.custom_emails.#", "2"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.0.custom_emails.0", fmt.Sprintf("acctest1-%d@example.com", data.RandomInteger)), - resource.TestCheckResourceAttr(data.ResourceName, "notification.0.email.0.custom_emails.1", fmt.Sprintf("acctest2-%d@example.com", data.RandomInteger)), - ), - }, - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_recurrence(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_recurrence(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.name", "recurrence"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "1"), - ), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_recurrenceUpdate(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_recurrence(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.#", "3"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.0", "Monday"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.1", "Wednesday"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.2", "Friday"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.hours.0", "18"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.minutes.0", "0"), - ), - }, - { - Config: testAccAzureRMAutoScaleSetting_recurrenceUpdated(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.#", "3"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.0", "Monday"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.1", "Tuesday"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.days.2", "Wednesday"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.hours.0", "20"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.recurrence.0.minutes.0", "15"), - ), - }, - }, - }) -} - -func TestAccAzureRMAutoScaleSetting_fixedDate(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_autoscale_setting", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMAutoScaleSettingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMAutoScaleSetting_fixedDate(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMAutoScaleSettingExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.name", "fixedDate"), - resource.TestCheckResourceAttr(data.ResourceName, "profile.0.fixed_date.#", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "notification.#", "0"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testCheckAzureRMAutoScaleSettingExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.AutoscaleSettingsClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - autoscaleSettingName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for AutoScale Setting: %s", autoscaleSettingName) - } - - resp, err := conn.Get(ctx, resourceGroup, autoscaleSettingName) - if err != nil { - return fmt.Errorf("Bad: Get on AutoScale Setting: %+v", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: AutoScale Setting %q (Resource Group: %q) does not exist", autoscaleSettingName, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMAutoScaleSettingDestroy(s *terraform.State) error { - conn := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.AutoscaleSettingsClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_autoscale_setting" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(ctx, resourceGroup, name) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("AutoScale Setting still exists:\n%#v", resp) - } - } - - return nil -} - -func testAccAzureRMAutoScaleSetting_basic(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "metricRules" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_requiresImport(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_basic(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "import" { - name = "${azurerm_autoscale_setting.test.name}" - resource_group_name = "${azurerm_autoscale_setting.test.resource_group_name}" - location = "${azurerm_autoscale_setting.test.location}" - target_resource_id = "${azurerm_autoscale_setting.test.target_resource_id}" - - profile { - name = "metricRules" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } -} -`, template) -} - -func testAccAzureRMAutoScaleSetting_multipleProfiles(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "primary" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Decrease" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } - - profile { - name = "secondary" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - recurrence { - timezone = "Pacific Standard Time" - - days = [ - "Monday", - "Wednesday", - "Friday", - ] - - hours = [18] - minutes = [0] - } - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_multipleRules(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - enabled = true - - profile { - name = "metricRules" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "LessThan" - threshold = 25 - } - - scale_action { - direction = "Decrease" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_capacity(data acceptance.TestData, min int, max int, defaultVal int) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - enabled = false - - profile { - name = "metricRules" - - capacity { - default = %d - minimum = %d - maximum = %d - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } -} -`, template, data.RandomInteger, defaultVal, min, max) -} - -func testAccAzureRMAutoScaleSetting_email(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "metricRules" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } - - notification { - email { - send_to_subscription_administrator = false - send_to_subscription_co_administrator = false - custom_emails = ["acctest1-%d@example.com"] - } - } -} -`, template, data.RandomInteger, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_emailUpdated(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "metricRules" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - rule { - metric_trigger { - metric_name = "Percentage CPU" - metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - time_grain = "PT1M" - statistic = "Average" - time_window = "PT5M" - time_aggregation = "Average" - operator = "GreaterThan" - threshold = 75 - } - - scale_action { - direction = "Increase" - type = "ChangeCount" - value = 1 - cooldown = "PT1M" - } - } - } - - notification { - email { - send_to_subscription_administrator = false - send_to_subscription_co_administrator = false - custom_emails = ["acctest1-%d@example.com", "acctest2-%d@example.com"] - } - } -} -`, template, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_recurrence(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "recurrence" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - recurrence { - timezone = "Pacific Standard Time" - - days = [ - "Monday", - "Wednesday", - "Friday", - ] - - hours = [18] - minutes = [0] - } - } - - notification { - email { - send_to_subscription_administrator = false - send_to_subscription_co_administrator = false - } - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_recurrenceUpdated(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "recurrence" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - recurrence { - timezone = "Pacific Standard Time" - - days = [ - "Monday", - "Tuesday", - "Wednesday", - ] - - hours = [20] - minutes = [15] - } - } - - notification { - email { - send_to_subscription_administrator = false - send_to_subscription_co_administrator = false - } - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_fixedDate(data acceptance.TestData) string { - template := testAccAzureRMAutoScaleSetting_template(data) - return fmt.Sprintf(` -%s - -resource "azurerm_autoscale_setting" "test" { - name = "acctestautoscale-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - target_resource_id = "${azurerm_virtual_machine_scale_set.test.id}" - - profile { - name = "fixedDate" - - capacity { - default = 1 - minimum = 1 - maximum = 30 - } - - fixed_date { - timezone = "Pacific Standard Time" - start = "2020-06-18T00:00:00Z" - end = "2020-06-18T23:59:59Z" - } - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMAutoScaleSetting_template(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "internal" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_virtual_machine_scale_set" "test" { - name = "acctvmss-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - upgrade_policy_mode = "Automatic" - single_placement_group = "false" - - sku { - name = "Standard_DS1_v2" - tier = "Standard" - capacity = 30 - } - - os_profile { - computer_name_prefix = "testvm-%d" - admin_username = "myadmin" - admin_password = "Passwword1234" - } - - network_profile { - name = "TestNetworkProfile-%d" - primary = true - - ip_configuration { - name = "TestIPConfiguration" - subnet_id = "${azurerm_subnet.test.id}" - primary = true - } - } - - storage_profile_os_disk { - name = "" - caching = "ReadWrite" - create_option = "FromImage" - managed_disk_type = "StandardSSD_LRS" - } - - storage_profile_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} diff --git a/azurerm/internal/services/monitor/tests/resource_arm_metric_alertrule_test.go b/azurerm/internal/services/monitor/tests/resource_arm_metric_alertrule_test.go deleted file mode 100644 index 9fad64b86ac5..000000000000 --- a/azurerm/internal/services/monitor/tests/resource_arm_metric_alertrule_test.go +++ /dev/null @@ -1,483 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func TestValidateMetricAlertRuleTags(t *testing.T) { - cases := []struct { - Name string - Value map[string]interface{} - ErrCount int - }{ - { - Name: "Single Valid", - Value: map[string]interface{}{ - "hello": "world", - }, - ErrCount: 0, - }, - { - Name: "Single Invalid", - Value: map[string]interface{}{ - "$Type": "hello/world", - }, - ErrCount: 1, - }, - { - Name: "Single Invalid lowercase", - Value: map[string]interface{}{ - "$type": "hello/world", - }, - ErrCount: 1, - }, - { - Name: "Multiple Valid", - Value: map[string]interface{}{ - "hello": "world", - "foo": "bar", - }, - ErrCount: 0, - }, - { - Name: "Multiple Invalid", - Value: map[string]interface{}{ - "hello": "world", - "$type": "Microsoft.Foo/Bar", - }, - ErrCount: 1, - }, - } - - for _, tc := range cases { - _, errors := monitor.ValidateMetricAlertRuleTags(tc.Value, "azurerm_metric_alert_rule") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected %q to return %d errors but returned %d", tc.Name, tc.ErrCount, len(errors)) - } - } -} - -func TestAccAzureRMMetricAlertRule_virtualMachineCpu(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_metric_alertrule", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMetricAlertRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMMetricAlertRule_virtualMachineCpu(data, true), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMetricAlertRuleExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - { - Config: testAccAzureRMMetricAlertRule_virtualMachineCpu(data, false), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMetricAlertRuleExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "false"), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - { - ResourceName: data.ResourceName, - ImportState: true, - ImportStateVerify: true, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMetricAlertRuleExists(data.ResourceName), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - }, - }) -} - -func TestAccAzureRMMetricAlertRule_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_metric_alertrule", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMetricAlertRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMMetricAlertRule_virtualMachineCpu(data, true), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMetricAlertRuleExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMMetricAlertRule_requiresImport(data, true), - ExpectError: acceptance.RequiresImportError("azurerm_metric_alertrule"), - }, - }, - }) -} - -func TestAccAzureRMMetricAlertRule_sqlDatabaseStorage(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_metric_alertrule", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMetricAlertRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMMetricAlertRule_sqlDatabaseStorage(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMetricAlertRuleExists(data.ResourceName), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - }, - }) -} - -func testCheckAzureRMMetricAlertRuleExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.AlertRulesClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for Alert Rule: %s", name) - } - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Alert Rule %q (resource group: %q) does not exist", name, resourceGroup) - } - - return fmt.Errorf("Bad: Get on monitorAlertRulesClient: %+v", err) - } - - return nil - } -} - -func testCheckAzureRMMetricAlertRuleDestroy(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.AlertRulesClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_metric_alertrule" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := client.Get(ctx, resourceGroup, name) - - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return nil - } - - return err - } - - return fmt.Errorf("Alert Rule still exists:\n%#v", resp) - } - - return nil -} - -func testAccAzureRMMetricAlertRule_virtualMachineCpu(data acceptance.TestData, enabled bool) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "osd-%d" - caching = "ReadWrite" - create_option = "FromImage" - disk_size_gb = "50" - managed_disk_type = "Standard_LRS" - } - - os_profile { - computer_name = "hn%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - tags = { - environment = "Production" - cost-center = "Ops" - } -} - -resource "azurerm_metric_alertrule" "test" { - name = "${azurerm_virtual_machine.test.name}-cpu" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - - description = "An alert rule to watch the metric Percentage CPU" - - enabled = %t - - resource_id = "${azurerm_virtual_machine.test.id}" - metric_name = "Percentage CPU" - operator = "GreaterThan" - threshold = 75 - aggregation = "Average" - period = "PT5M" - - email_action { - send_to_service_owners = false - - custom_emails = [ - "support@azure.microsoft.com", - ] - } - - webhook_action { - service_uri = "https://requestb.in/18jamc41" - - properties = { - severity = "incredible" - acceptance_test = "true" - } - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, enabled) -} - -func testAccAzureRMMetricAlertRule_requiresImport(data acceptance.TestData, enabled bool) string { - template := testAccAzureRMMetricAlertRule_virtualMachineCpu(data, enabled) - return fmt.Sprintf(` -%s - -resource "azurerm_metric_alertrule" "import" { - name = "${azurerm_metric_alertrule.test.name}" - resource_group_name = "${azurerm_metric_alertrule.test.resource_group_name}" - location = "${azurerm_metric_alertrule.test.location}" - description = "${azurerm_metric_alertrule.test.description}" - enabled = "${azurerm_metric_alertrule.test.enabled}" - - resource_id = "${azurerm_virtual_machine.test.id}" - metric_name = "Percentage CPU" - operator = "GreaterThan" - threshold = 75 - aggregation = "Average" - period = "PT5M" - - email_action { - send_to_service_owners = false - - custom_emails = [ - "support@azure.microsoft.com", - ] - } - - webhook_action { - service_uri = "https://requestb.in/18jamc41" - - properties = { - severity = "incredible" - acceptance_test = "true" - } - } -} -`, template) -} - -func testAccAzureRMMetricAlertRule_sqlDatabaseStorage(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%[1]d" - location = "%[2]s" -} - - -resource "azurerm_sql_server" "test" { - name = "acctestsqlserver%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "mradministrator" - administrator_login_password = "thisIsDog11" -} - -resource "azurerm_sql_database" "test" { - name = "acctestdb%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - server_name = "${azurerm_sql_server.test.name}" - location = "${azurerm_resource_group.test.location}" - edition = "Standard" - collation = "SQL_Latin1_General_CP1_CI_AS" - max_size_bytes = "1073741824" - requested_service_objective_name = "S0" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%[1]d" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%[1]d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%[1]d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "osd-%[1]d" - caching = "ReadWrite" - create_option = "FromImage" - disk_size_gb = "50" - managed_disk_type = "Standard_LRS" - } - - os_profile { - computer_name = "hn%[1]d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - tags = { - environment = "Production" - cost-center = "Ops" - } -} - -resource "azurerm_metric_alertrule" "test" { - name = "${azurerm_sql_database.test.name}-storage" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - - description = "An alert rule to watch the metric Storage" - - enabled = true - - resource_id = "${azurerm_sql_database.test.id}" - metric_name = "storage" - operator = "GreaterThan" - threshold = 1073741824 - aggregation = "Maximum" - period = "PT10M" - - email_action { - send_to_service_owners = false - - custom_emails = [ - "support@azure.microsoft.com", - ] - } - - webhook_action { - service_uri = "https://requestb.in/18jamc41" - - properties = { - severity = "incredible" - acceptance_test = "true" - } - } -} -`, data.RandomInteger, data.Locations.Primary) -} diff --git a/azurerm/internal/services/monitor/tests/resource_arm_monitor_metric_alertrule_test.go b/azurerm/internal/services/monitor/tests/resource_arm_monitor_metric_alertrule_test.go deleted file mode 100644 index cd71bce28573..000000000000 --- a/azurerm/internal/services/monitor/tests/resource_arm_monitor_metric_alertrule_test.go +++ /dev/null @@ -1,462 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func TestValidateMonitorMetricAlertRuleTags(t *testing.T) { - cases := []struct { - Name string - Value map[string]interface{} - ErrCount int - }{ - { - Name: "Single Valid", - Value: map[string]interface{}{ - "hello": "world", - }, - ErrCount: 0, - }, - { - Name: "Single Invalid", - Value: map[string]interface{}{ - "$Type": "hello/world", - }, - ErrCount: 1, - }, - { - Name: "Single Invalid lowercase", - Value: map[string]interface{}{ - "$type": "hello/world", - }, - ErrCount: 1, - }, - { - Name: "Multiple Valid", - Value: map[string]interface{}{ - "hello": "world", - "foo": "bar", - }, - ErrCount: 0, - }, - { - Name: "Multiple Invalid", - Value: map[string]interface{}{ - "hello": "world", - "$type": "Microsoft.Foo/Bar", - }, - ErrCount: 1, - }, - } - - for _, tc := range cases { - _, errors := monitor.ValidateMonitorMetricAlertRuleTags(tc.Value, "azurerm_metric_alert_rule") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected %q to return %d errors but returned %d", tc.Name, tc.ErrCount, len(errors)) - } - } -} - -func TestAccAzureRMMonitorMetricAlertRule_virtualMachineCpu(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_monitor_metric_alertrule", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMonitorMetricAlertRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMMonitorMetricAlertRule_virtualMachineCpu(data, true), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMonitorMetricAlertRuleExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "true"), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - { - Config: testAccAzureRMMonitorMetricAlertRule_virtualMachineCpu(data, false), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMonitorMetricAlertRuleExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "enabled", "false"), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - { - ResourceName: data.ResourceName, - ImportState: true, - ImportStateVerify: true, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMonitorMetricAlertRuleExists(data.ResourceName), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - }, - }) -} - -func TestAccAzureRMMonitorMetricAlertRule_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_monitor_metric_alertrule", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMonitorMetricAlertRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMMonitorMetricAlertRule_virtualMachineCpu(data, true), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMonitorMetricAlertRuleExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMMonitorMetricAlertRule_requiresImport(data, true), - ExpectError: acceptance.RequiresImportError("azurerm_monitor_metric_alertrule"), - }, - }, - }) -} - -func TestAccAzureRMMonitorMetricAlertRule_sqlDatabaseStorage(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_monitor_metric_alertrule", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMonitorMetricAlertRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMMonitorMetricAlertRule_sqlDatabaseStorage(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMonitorMetricAlertRuleExists(data.ResourceName), - resource.TestCheckNoResourceAttr(data.ResourceName, "tags.$type"), - ), - }, - }, - }) -} - -func testCheckAzureRMMonitorMetricAlertRuleExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.AlertRulesClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for Alert Rule: %s", name) - } - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Alert Rule %q (resource group: %q) does not exist", name, resourceGroup) - } - - return fmt.Errorf("Bad: Get on monitorAlertRulesClient: %+v", err) - } - - return nil - } -} - -func testCheckAzureRMMonitorMetricAlertRuleDestroy(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.AlertRulesClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_monitor_metric_alertrule" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := client.Get(ctx, resourceGroup, name) - - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return nil - } - - return err - } - - return fmt.Errorf("Alert Rule still exists:\n%#v", resp) - } - - return nil -} - -func testAccAzureRMMonitorMetricAlertRule_virtualMachineCpu(data acceptance.TestData, enabled bool) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "osd-%d" - caching = "ReadWrite" - create_option = "FromImage" - disk_size_gb = "50" - managed_disk_type = "Standard_LRS" - } - - os_profile { - computer_name = "hn%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - tags = { - environment = "Production" - cost-center = "Ops" - } -} - -resource "azurerm_monitor_metric_alertrule" "test" { - name = "${azurerm_virtual_machine.test.name}-cpu" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - - description = "An alert rule to watch the metric Percentage CPU" - - enabled = %t - - resource_id = "${azurerm_virtual_machine.test.id}" - metric_name = "Percentage CPU" - operator = "GreaterThan" - threshold = 75 - aggregation = "Average" - period = "PT5M" - - email_action { - send_to_service_owners = false - - custom_emails = [ - "support@azure.microsoft.com", - ] - } - - webhook_action { - service_uri = "https://requestb.in/18jamc41" - - properties = { - severity = "incredible" - acceptance_test = "true" - } - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, enabled) -} - -func testAccAzureRMMonitorMetricAlertRule_requiresImport(data acceptance.TestData, enabled bool) string { - template := testAccAzureRMMonitorMetricAlertRule_virtualMachineCpu(data, enabled) - return fmt.Sprintf(` -%s - -resource "azurerm_monitor_metric_alertrule" "import" { - name = "${azurerm_monitor_metric_alertrule.test.name}" - resource_group_name = "${azurerm_monitor_metric_alertrule.test.resource_group_name}" - location = "${azurerm_monitor_metric_alertrule.test.location}" - description = "${azurerm_monitor_metric_alertrule.test.description}" - enabled = "${azurerm_monitor_metric_alertrule.test.enabled}" - - resource_id = "${azurerm_virtual_machine.test.id}" - metric_name = "Percentage CPU" - operator = "GreaterThan" - threshold = 75 - aggregation = "Average" - period = "PT5M" - - email_action { - send_to_service_owners = false - - custom_emails = [ - "support@azure.microsoft.com", - ] - } - - webhook_action { - service_uri = "https://requestb.in/18jamc41" - - properties = { - severity = "incredible" - acceptance_test = "true" - } - } -} -`, template) -} - -func testAccAzureRMMonitorMetricAlertRule_sqlDatabaseStorage(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "osd-%d" - caching = "ReadWrite" - create_option = "FromImage" - disk_size_gb = "50" - managed_disk_type = "Standard_LRS" - } - - os_profile { - computer_name = "hn%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - tags = { - environment = "Production" - cost-center = "Ops" - } -} - -resource "azurerm_monitor_metric_alertrule" "test" { - name = "${azurerm_sql_database.test.name}-storage" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - - description = "An alert rule to watch the metric Storage" - - enabled = true - - resource_id = "${azurerm_sql_database.test.id}" - metric_name = "storage" - operator = "GreaterThan" - threshold = 1073741824 - aggregation = "Maximum" - period = "PT10M" - - email_action { - send_to_service_owners = false - - custom_emails = [ - "support@azure.microsoft.com", - ] - } - - webhook_action { - service_uri = "https://requestb.in/18jamc41" - - properties = { - severity = "incredible" - acceptance_test = "true" - } - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} diff --git a/azurerm/internal/services/network/data_source_private_link_endpoint_connection.go b/azurerm/internal/services/network/data_source_private_link_endpoint_connection.go deleted file mode 100644 index 505d1943146b..000000000000 --- a/azurerm/internal/services/network/data_source_private_link_endpoint_connection.go +++ /dev/null @@ -1,167 +0,0 @@ -package network - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func dataSourceArmPrivateLinkEndpointConnection() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: `The 'azurerm_private_link_endpoint_connection' resource is being deprecated in favour of the renamed version 'azurerm_private_endpoint_connection'. - -Information on migrating to the renamed resource can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-between-renamed-resources.html - -As such the existing 'azurerm_private_link_endpoint_connection' resource is deprecated and will be removed in the next major version of the AzureRM Provider (2.0). -`, - - Read: dataSourceArmPrivateLinkEndpointConnectionRead, - Timeouts: &schema.ResourceTimeout{ - Read: schema.DefaultTimeout(5 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: ValidatePrivateLinkName, - }, - - "location": azure.SchemaLocationForDataSource(), - - "resource_group_name": azure.SchemaResourceGroupNameForDataSource(), - - "private_service_connection": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Computed: true, - }, - "request_response": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "private_ip_address": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - } -} - -func dataSourceArmPrivateLinkEndpointConnectionRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.PrivateEndpointClient - nicsClient := meta.(*clients.Client).Network.InterfacesClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - - resp, err := client.Get(ctx, resourceGroup, name, "") - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error reading Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - if resp.ID == nil || *resp.ID == "" { - return fmt.Errorf("API returns a nil/empty id on Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - d.SetId(*resp.ID) - d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - if props := resp.PrivateEndpointProperties; props != nil { - privateIpAddress := "" - - if nics := props.NetworkInterfaces; nics != nil && len(*nics) > 0 { - nic := (*nics)[0] - if nic.ID != nil && *nic.ID != "" { - privateIpAddress = getPrivateIpAddress(ctx, nicsClient, *nic.ID) - } - } - - if err := d.Set("private_service_connection", dataSourceFlattenArmPrivateLinkEndpointServiceConnection(props.PrivateLinkServiceConnections, props.ManualPrivateLinkServiceConnections, privateIpAddress)); err != nil { - return fmt.Errorf("Error setting `private_service_connection`: %+v", err) - } - } - - return nil -} - -func dataSourceFlattenArmPrivateLinkEndpointServiceConnection(serviceConnections *[]network.PrivateLinkServiceConnection, manualServiceConnections *[]network.PrivateLinkServiceConnection, privateIpAddress string) []interface{} { - results := make([]interface{}, 0) - if serviceConnections == nil && manualServiceConnections == nil { - return results - } - - if serviceConnections != nil { - for _, item := range *serviceConnections { - result := make(map[string]interface{}) - result["private_ip_address"] = privateIpAddress - - if v := item.Name; v != nil { - result["name"] = *v - } - if props := item.PrivateLinkServiceConnectionProperties; props != nil { - if v := props.PrivateLinkServiceConnectionState; v != nil { - if s := v.Status; s != nil { - result["status"] = *s - } - if d := v.Description; d != nil { - result["request_response"] = *d - } - } - } - - results = append(results, result) - } - } - - if manualServiceConnections != nil { - for _, item := range *manualServiceConnections { - result := make(map[string]interface{}) - result["private_ip_address"] = privateIpAddress - - if v := item.Name; v != nil { - result["name"] = *v - } - if props := item.PrivateLinkServiceConnectionProperties; props != nil { - if v := props.PrivateLinkServiceConnectionState; v != nil { - if s := v.Status; s != nil { - result["status"] = *s - } - if d := v.Description; d != nil { - result["request_response"] = *d - } - } - } - - results = append(results, result) - } - } - - return results -} diff --git a/azurerm/internal/services/network/registration.go b/azurerm/internal/services/network/registration.go index 53b0e69c5603..a9fbaafdfc57 100644 --- a/azurerm/internal/services/network/registration.go +++ b/azurerm/internal/services/network/registration.go @@ -32,7 +32,6 @@ func (r Registration) SupportedDataSources() map[string]*schema.Resource { "azurerm_network_interface": dataSourceArmNetworkInterface(), "azurerm_network_security_group": dataSourceArmNetworkSecurityGroup(), "azurerm_network_watcher": dataSourceArmNetworkWatcher(), - "azurerm_private_link_endpoint_connection": dataSourceArmPrivateLinkEndpointConnection(), "azurerm_private_endpoint_connection": dataSourceArmPrivateEndpointConnection(), "azurerm_private_link_service": dataSourceArmPrivateLinkService(), "azurerm_private_link_service_endpoint_connections": dataSourceArmPrivateLinkServiceEndpointConnections(), @@ -54,8 +53,6 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { "azurerm_application_gateway": resourceArmApplicationGateway(), "azurerm_application_security_group": resourceArmApplicationSecurityGroup(), "azurerm_bastion_host": resourceArmBastionHost(), - "azurerm_connection_monitor": resourceArmConnectionMonitor(), - "azurerm_ddos_protection_plan": resourceArmDDoSProtectionPlan(), "azurerm_express_route_circuit_authorization": resourceArmExpressRouteCircuitAuthorization(), "azurerm_express_route_circuit_peering": resourceArmExpressRouteCircuitPeering(), "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), @@ -85,7 +82,6 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { "azurerm_network_profile": resourceArmNetworkProfile(), "azurerm_packet_capture": resourceArmPacketCapture(), "azurerm_point_to_site_vpn_gateway": resourceArmPointToSiteVPNGateway(), - "azurerm_private_link_endpoint": resourceArmPrivateLinkEndpoint(), "azurerm_private_endpoint": resourceArmPrivateEndpoint(), "azurerm_private_link_service": resourceArmPrivateLinkService(), "azurerm_public_ip": resourceArmPublicIp(), diff --git a/azurerm/internal/services/network/resource_arm_connection_monitor.go b/azurerm/internal/services/network/resource_arm_connection_monitor.go deleted file mode 100644 index e9a794a12027..000000000000 --- a/azurerm/internal/services/network/resource_arm_connection_monitor.go +++ /dev/null @@ -1,351 +0,0 @@ -package network - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network" - "github.com/hashicorp/go-azure-helpers/response" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmConnectionMonitor() *schema.Resource { - return &schema.Resource{ - Create: resourceArmConnectionMonitorCreateUpdate, - Read: resourceArmConnectionMonitorRead, - Update: resourceArmConnectionMonitorCreateUpdate, - Delete: resourceArmConnectionMonitorDelete, - - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - DeprecationMessage: `The 'azurerm_connection_monitor' resource is deprecated in favour of the renamed version 'azurerm_network_connection_monitor'. - -Information on migrating to the renamed resource can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-between-renamed-resources.html - -As such the existing 'azurerm_connection_monitor' resource is deprecated and will be removed in the next major version of the AzureRM Provider (2.0). -`, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - - "resource_group_name": azure.SchemaResourceGroupName(), - - "network_watcher_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - - "location": azure.SchemaLocation(), - - "auto_start": { - Type: schema.TypeBool, - Optional: true, - ForceNew: true, - Default: true, - }, - - "interval_in_seconds": { - Type: schema.TypeInt, - Optional: true, - Default: 60, - ValidateFunc: validation.IntAtLeast(30), - }, - - "source": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "virtual_machine_id": { - Type: schema.TypeString, - Required: true, - ValidateFunc: azure.ValidateResourceID, - }, - "port": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - ValidateFunc: validate.PortNumberOrZero, - }, - }, - }, - }, - - "destination": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "virtual_machine_id": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: azure.ValidateResourceID, - ConflictsWith: []string{"destination.0.address"}, - }, - "address": { - Type: schema.TypeString, - Optional: true, - ConflictsWith: []string{"destination.0.virtual_machine_id"}, - }, - "port": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validate.PortNumber, - }, - }, - }, - }, - - "tags": tags.Schema(), - }, - } -} - -func resourceArmConnectionMonitorCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.ConnectionMonitorsClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - name := d.Get("name").(string) - watcherName := d.Get("network_watcher_name").(string) - resourceGroup := d.Get("resource_group_name").(string) - location := azure.NormalizeLocation(d.Get("location").(string)) - autoStart := d.Get("auto_start").(bool) - intervalInSeconds := int32(d.Get("interval_in_seconds").(int)) - - source, err := expandArmConnectionMonitorSource(d) - if err != nil { - return err - } - - dest, err := expandArmConnectionMonitorDestination(d) - if err != nil { - return err - } - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, watcherName, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing Connection Monitor %q (Watcher %q / Resource Group %q): %s", name, watcherName, resourceGroup, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_connection_monitor", *existing.ID) - } - } - - t := d.Get("tags").(map[string]interface{}) - - properties := network.ConnectionMonitor{ - Location: utils.String(location), - Tags: tags.Expand(t), - ConnectionMonitorParameters: &network.ConnectionMonitorParameters{ - Source: source, - Destination: dest, - AutoStart: utils.Bool(autoStart), - MonitoringIntervalInSeconds: utils.Int32(intervalInSeconds), - }, - } - - future, err := client.CreateOrUpdate(ctx, resourceGroup, watcherName, name, properties) - if err != nil { - return fmt.Errorf("Error creating Connection Monitor %q (Watcher %q / Resource Group %q): %+v", name, watcherName, resourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for completion of Connection Monitor %q (Watcher %q / Resource Group %q): %+v", name, watcherName, resourceGroup, err) - } - - resp, err := client.Get(ctx, resourceGroup, watcherName, name) - if err != nil { - return fmt.Errorf("Error retrieving Connection Monitor %q (Watcher %q / Resource Group %q): %+v", name, watcherName, resourceGroup, err) - } - if resp.ID == nil { - return fmt.Errorf("Cannot read Connection Monitor %q (Watcher %q / Resource Group %q) ID", name, watcherName, resourceGroup) - } - - d.SetId(*resp.ID) - - return resourceArmConnectionMonitorRead(d, meta) -} - -func resourceArmConnectionMonitorRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.ConnectionMonitorsClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - watcherName := id.Path["networkWatchers"] - name := id.Path["connectionMonitors"] - - resp, err := client.Get(ctx, resourceGroup, watcherName, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error reading Connection Monitor %q (Watcher %q / Resource Group %q) %+v", name, watcherName, resourceGroup, err) - } - - d.Set("name", name) - d.Set("network_watcher_name", watcherName) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - if props := resp.ConnectionMonitorResultProperties; props != nil { - d.Set("auto_start", props.AutoStart) - d.Set("interval_in_seconds", props.MonitoringIntervalInSeconds) - - source := flattenArmConnectionMonitorSource(props.Source) - if err := d.Set("source", source); err != nil { - return fmt.Errorf("Error setting `source`: %+v", err) - } - - dest := flattenArmConnectionMonitorDestination(props.Destination) - if err := d.Set("destination", dest); err != nil { - return fmt.Errorf("Error setting `destination`: %+v", err) - } - } - - return tags.FlattenAndSet(d, resp.Tags) -} - -func resourceArmConnectionMonitorDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.ConnectionMonitorsClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - watcherName := id.Path["networkWatchers"] - name := id.Path["connectionMonitors"] - - future, err := client.Delete(ctx, resourceGroup, watcherName, name) - if err != nil { - if !response.WasNotFound(future.Response()) { - return fmt.Errorf("Error deleting Connection Monitor %q (Watcher %q / Resource Group %q): %+v", name, watcherName, resourceGroup, err) - } - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for the deletion of Connection Monitor %q (Watcher %q / Resource Group %q): %+v", name, watcherName, resourceGroup, err) - } - - return nil -} - -func flattenArmConnectionMonitorSource(input *network.ConnectionMonitorSource) []interface{} { - if input == nil { - return []interface{}{} - } - - output := make(map[string]interface{}) - - if resourceID := input.ResourceID; resourceID != nil { - output["virtual_machine_id"] = *resourceID - } - if port := input.Port; port != nil { - output["port"] = *port - } - - return []interface{}{output} -} - -func expandArmConnectionMonitorSource(d *schema.ResourceData) (*network.ConnectionMonitorSource, error) { - sources := d.Get("source").([]interface{}) - source := sources[0].(map[string]interface{}) - - monitorSource := network.ConnectionMonitorSource{} - if v := source["virtual_machine_id"]; v != "" { - monitorSource.ResourceID = utils.String(v.(string)) - } - if v := source["port"]; v != "" { - monitorSource.Port = utils.Int32(int32(v.(int))) - } - - return &monitorSource, nil -} - -func flattenArmConnectionMonitorDestination(input *network.ConnectionMonitorDestination) []interface{} { - if input == nil { - return []interface{}{} - } - - output := make(map[string]interface{}) - - // When monitoring a VM, the address field will contain the current address - // of the VM. We only want to copy over the address field if the virtual - // machine field is not set to avoid unwanted diffs. - if resourceID := input.ResourceID; resourceID != nil { - output["virtual_machine_id"] = *resourceID - } else if address := input.Address; address != nil { - output["address"] = *address - } - - if port := input.Port; port != nil { - output["port"] = *port - } - - return []interface{}{output} -} - -func expandArmConnectionMonitorDestination(d *schema.ResourceData) (*network.ConnectionMonitorDestination, error) { - dests := d.Get("destination").([]interface{}) - dest := dests[0].(map[string]interface{}) - - monitorDest := network.ConnectionMonitorDestination{} - - if v := dest["virtual_machine_id"]; v != "" { - monitorDest.ResourceID = utils.String(v.(string)) - } - if v := dest["address"]; v != "" { - monitorDest.Address = utils.String(v.(string)) - } - if v := dest["port"]; v != "" { - monitorDest.Port = utils.Int32(int32(v.(int))) - } - - if monitorDest.ResourceID == nil && monitorDest.Address == nil { - return nil, fmt.Errorf("Error: either `destination.virtual_machine_id` or `destination.address` must be specified") - } - - return &monitorDest, nil -} diff --git a/azurerm/internal/services/network/resource_arm_ddos_protection_plan.go b/azurerm/internal/services/network/resource_arm_ddos_protection_plan.go deleted file mode 100644 index 10c5377ba10e..000000000000 --- a/azurerm/internal/services/network/resource_arm_ddos_protection_plan.go +++ /dev/null @@ -1,254 +0,0 @@ -package network - -import ( - "fmt" - "log" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/locks" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -const azureDDoSProtectionPlanResourceName = "azurerm_ddos_protection_plan" - -func resourceArmDDoSProtectionPlan() *schema.Resource { - return &schema.Resource{ - Create: resourceArmDDoSProtectionPlanCreateUpdate, - Read: resourceArmDDoSProtectionPlanRead, - Update: resourceArmDDoSProtectionPlanCreateUpdate, - Delete: resourceArmDDoSProtectionPlanDelete, - - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - DeprecationMessage: `The 'azurerm_ddos_protection_plan' resource is deprecated in favour of the renamed version 'azurerm_network_ddos_protection_plan'. - -Information on migrating to the renamed resource can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-between-renamed-resources.html - -As such the existing 'azurerm_ddos_protection_plan' resource is deprecated and will be removed in the next major version of the AzureRM Provider (2.0). -`, - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": azure.SchemaLocation(), - - "resource_group_name": azure.SchemaResourceGroupName(), - - "virtual_network_ids": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - - "tags": tags.Schema(), - }, - } -} - -func resourceArmDDoSProtectionPlanCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.DDOSProtectionPlansClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - log.Printf("[INFO] preparing arguments for DDoS protection plan creation") - - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing DDoS Protection Plan %q (Resource Group %q): %s", name, resourceGroup, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_ddos_protection_plan", *existing.ID) - } - } - - location := azure.NormalizeLocation(d.Get("location").(string)) - t := d.Get("tags").(map[string]interface{}) - - vnetsToLock, err := extractVnetNames(d) - if err != nil { - return fmt.Errorf("Error extracting names of Virtual Network: %+v", err) - } - - locks.ByName(name, azureDDoSProtectionPlanResourceName) - defer locks.UnlockByName(name, azureDDoSProtectionPlanResourceName) - - locks.MultipleByName(vnetsToLock, VirtualNetworkResourceName) - defer locks.UnlockMultipleByName(vnetsToLock, VirtualNetworkResourceName) - - parameters := network.DdosProtectionPlan{ - Location: &location, - Tags: tags.Expand(t), - } - - future, err := client.CreateOrUpdate(ctx, resourceGroup, name, parameters) - if err != nil { - return fmt.Errorf("Error creating/updating DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for creation/update of DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - plan, err := client.Get(ctx, resourceGroup, name) - if err != nil { - return fmt.Errorf("Error retrieving DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if plan.ID == nil { - return fmt.Errorf("Cannot read DDoS Protection Plan %q (Resource Group %q) ID", name, resourceGroup) - } - - d.SetId(*plan.ID) - - return resourceArmDDoSProtectionPlanRead(d, meta) -} - -func resourceArmDDoSProtectionPlanRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.DDOSProtectionPlansClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["ddosProtectionPlans"] - - plan, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(plan.Response) { - log.Printf("[DEBUG] DDoS Protection Plan %q was not found in Resource Group %q - removing from state!", name, resourceGroup) - d.SetId("") - return nil - } - - return fmt.Errorf("Error making Read request on DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - d.Set("name", plan.Name) - d.Set("resource_group_name", resourceGroup) - if location := plan.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - if props := plan.DdosProtectionPlanPropertiesFormat; props != nil { - vNetIDs := flattenArmVirtualNetworkIDs(props.VirtualNetworks) - if err := d.Set("virtual_network_ids", vNetIDs); err != nil { - return fmt.Errorf("Error setting `virtual_network_ids`: %+v", err) - } - } - - return tags.FlattenAndSet(d, plan.Tags) -} - -func resourceArmDDoSProtectionPlanDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.DDOSProtectionPlansClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["ddosProtectionPlans"] - - read, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(read.Response) { - // deleted outside of TF - log.Printf("[DEBUG] DDoS Protection Plan %q was not found in Resource Group %q - assuming removed!", name, resourceGroup) - return nil - } - - return fmt.Errorf("Error retrieving DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - vnetsToLock, err := extractVnetNames(d) - if err != nil { - return fmt.Errorf("Error extracting names of Virtual Network: %+v", err) - } - - locks.ByName(name, azureDDoSProtectionPlanResourceName) - defer locks.UnlockByName(name, azureDDoSProtectionPlanResourceName) - - locks.MultipleByName(vnetsToLock, VirtualNetworkResourceName) - defer locks.UnlockMultipleByName(vnetsToLock, VirtualNetworkResourceName) - - future, err := client.Delete(ctx, resourceGroup, name) - if err != nil { - return fmt.Errorf("Error deleting DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for the deletion of DDoS Protection Plan %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - return err -} - -func extractVnetNames(d *schema.ResourceData) (*[]string, error) { - vnetIDs := d.Get("virtual_network_ids").([]interface{}) - vnetNames := make([]string, 0) - - for _, vnetID := range vnetIDs { - vnetResourceID, err := azure.ParseAzureResourceID(vnetID.(string)) - if err != nil { - return nil, err - } - - vnetName := vnetResourceID.Path["virtualNetworks"] - - if !azure.SliceContainsValue(vnetNames, vnetName) { - vnetNames = append(vnetNames, vnetName) - } - } - - return &vnetNames, nil -} - -func flattenArmVirtualNetworkIDs(input *[]network.SubResource) []string { - vnetIDs := make([]string, 0) - if input == nil { - return vnetIDs - } - - // if-continue is used to simplify the deeply nested if-else statement. - for _, subRes := range *input { - if subRes.ID != nil { - vnetIDs = append(vnetIDs, *subRes.ID) - } - } - - return vnetIDs -} diff --git a/azurerm/internal/services/network/resource_arm_network_ddos_protection_plan.go b/azurerm/internal/services/network/resource_arm_network_ddos_protection_plan.go index 3f8f2f8dfb53..e7664d5b366f 100644 --- a/azurerm/internal/services/network/resource_arm_network_ddos_protection_plan.go +++ b/azurerm/internal/services/network/resource_arm_network_ddos_protection_plan.go @@ -246,3 +246,23 @@ func flattenArmNetworkDDoSProtectionPlanVirtualNetworkIDs(input *[]network.SubRe return vnetIDs } + +func extractVnetNames(d *schema.ResourceData) (*[]string, error) { + vnetIDs := d.Get("virtual_network_ids").([]interface{}) + vnetNames := make([]string, 0) + + for _, vnetID := range vnetIDs { + vnetResourceID, err := azure.ParseAzureResourceID(vnetID.(string)) + if err != nil { + return nil, err + } + + vnetName := vnetResourceID.Path["virtualNetworks"] + + if !azure.SliceContainsValue(vnetNames, vnetName) { + vnetNames = append(vnetNames, vnetName) + } + } + + return &vnetNames, nil +} diff --git a/azurerm/internal/services/network/resource_arm_private_link_endpoint.go b/azurerm/internal/services/network/resource_arm_private_link_endpoint.go deleted file mode 100644 index b4f420a31649..000000000000 --- a/azurerm/internal/services/network/resource_arm_private_link_endpoint.go +++ /dev/null @@ -1,242 +0,0 @@ -package network - -import ( - "fmt" - "log" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network" - "github.com/hashicorp/go-azure-helpers/response" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmPrivateLinkEndpoint() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: `The 'azurerm_private_link_endpoint' resource is being deprecated in favour of the renamed version 'azurerm_private_endpoint'. - -Information on migrating to the renamed resource can be found here: https://terraform.io/docs/providers/azurerm/guides/migrating-between-renamed-resources.html - -As such the existing 'azurerm_private_link_endpoint' resource is deprecated and will be removed in the next major version of the AzureRM Provider (2.0). -`, - - Create: resourceArmPrivateLinkEndpointCreateUpdate, - Read: resourceArmPrivateLinkEndpointRead, - Update: resourceArmPrivateLinkEndpointCreateUpdate, - Delete: resourceArmPrivateLinkEndpointDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(60 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(60 * time.Minute), - Delete: schema.DefaultTimeout(60 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: ValidatePrivateLinkName, - }, - - "location": azure.SchemaLocation(), - - "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), - - "subnet_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - }, - - "private_service_connection": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: ValidatePrivateLinkName, - }, - "is_manual_connection": { - Type: schema.TypeBool, - Required: true, - ForceNew: true, - }, - "private_connection_resource_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - }, - "subresource_names": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: ValidatePrivateLinkSubResourceName, - }, - }, - "request_message": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringLenBetween(1, 140), - }, - }, - }, - }, - - // tags has been removed - // API Issue "Unable to remove Tags from Private Link Endpoint": https://github.com/Azure/azure-sdk-for-go/issues/6467 - }, - } -} - -func resourceArmPrivateLinkEndpointCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.PrivateEndpointClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - - if err := ValidatePrivateEndpointSettings(d); err != nil { - return fmt.Errorf("Error validating the configuration for the Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, name, "") - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_private_link_endpoint", *existing.ID) - } - } - - location := azure.NormalizeLocation(d.Get("location").(string)) - privateServiceConnections := d.Get("private_service_connection").([]interface{}) - subnetId := d.Get("subnet_id").(string) - - parameters := network.PrivateEndpoint{ - Location: utils.String(location), - PrivateEndpointProperties: &network.PrivateEndpointProperties{ - PrivateLinkServiceConnections: expandArmPrivateLinkEndpointServiceConnection(privateServiceConnections, false), - ManualPrivateLinkServiceConnections: expandArmPrivateLinkEndpointServiceConnection(privateServiceConnections, true), - Subnet: &network.Subnet{ - ID: utils.String(subnetId), - }, - }, - } - - future, err := client.CreateOrUpdate(ctx, resourceGroup, name, parameters) - if err != nil { - return fmt.Errorf("Error creating Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for creation of Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - resp, err := client.Get(ctx, resourceGroup, name, "") - if err != nil { - return fmt.Errorf("Error retrieving Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - if resp.ID == nil || *resp.ID == "" { - return fmt.Errorf("API returns a nil/empty id on Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - d.SetId(*resp.ID) - - return resourceArmPrivateLinkEndpointRead(d, meta) -} - -func resourceArmPrivateLinkEndpointRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.PrivateEndpointClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["privateEndpoints"] - - resp, err := client.Get(ctx, resourceGroup, name, "") - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[INFO] Private Link Endpoint %q does not exist - removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error reading Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - - if props := resp.PrivateEndpointProperties; props != nil { - flattenedConnection := flattenArmPrivateLinkEndpointServiceConnection(props.PrivateLinkServiceConnections, props.ManualPrivateLinkServiceConnections) - if err := d.Set("private_service_connection", flattenedConnection); err != nil { - return fmt.Errorf("Error setting `private_service_connection`: %+v", err) - } - - subnetId := "" - if subnet := props.Subnet; subnet != nil { - subnetId = *subnet.ID - } - d.Set("subnet_id", subnetId) - } - - // API Issue "Unable to remove Tags from Private Link Endpoint": https://github.com/Azure/azure-sdk-for-go/issues/6467 - return nil -} - -func resourceArmPrivateLinkEndpointDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Network.PrivateEndpointClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["privateEndpoints"] - - future, err := client.Delete(ctx, resourceGroup, name) - if err != nil { - if response.WasNotFound(future.Response()) { - return nil - } - return fmt.Errorf("Error deleting Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - if !response.WasNotFound(future.Response()) { - return fmt.Errorf("Error waiting for deletion of Private Link Endpoint %q (Resource Group %q): %+v", name, resourceGroup, err) - } - } - - return nil -} diff --git a/azurerm/internal/services/network/tests/data_source_private_link_endpoint_connection_test.go b/azurerm/internal/services/network/tests/data_source_private_link_endpoint_connection_test.go deleted file mode 100644 index ede0b0744a08..000000000000 --- a/azurerm/internal/services/network/tests/data_source_private_link_endpoint_connection_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" -) - -func TestAccDataSourceAzureRMPrivateLinkEndpointConnection_complete(t *testing.T) { - data := acceptance.BuildTestData(t, "data.azurerm_private_link_endpoint_connection", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourcePrivateLinkEndpointConnection_complete(data), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(data.ResourceName, "private_service_connection.0.status", "Approved"), - ), - }, - }, - }) -} - -func testAccDataSourcePrivateLinkEndpointConnection_complete(data acceptance.TestData) string { - return fmt.Sprintf(` -%s - -data "azurerm_private_link_endpoint_connection" "test" { - name = azurerm_private_link_endpoint.test.name - resource_group_name = azurerm_resource_group.test.name -} -`, testAccAzureRMPrivateLinkEndpoint_basic(data)) -} diff --git a/azurerm/internal/services/network/tests/resource_arm_connection_monitor_test.go b/azurerm/internal/services/network/tests/resource_arm_connection_monitor_test.go deleted file mode 100644 index 04240aa2f761..000000000000 --- a/azurerm/internal/services/network/tests/resource_arm_connection_monitor_test.go +++ /dev/null @@ -1,648 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "regexp" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" -) - -func testAccAzureRMConnectionMonitor_addressBasic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_basicAddressConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "resource_group_name"), - resource.TestCheckResourceAttr(data.ResourceName, "location", azure.NormalizeLocation(data.Locations.Primary)), - resource.TestCheckResourceAttr(data.ResourceName, "auto_start", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "interval_in_seconds", "60"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_basicAddressConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMConnectionMonitor_requiresImportConfig(data), - ExpectError: acceptance.RequiresImportError("azurerm_connection_monitor"), - }, - }, - }) -} - -func testAccAzureRMConnectionMonitor_addressComplete(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - autoStart := "false" - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_completeAddressConfig(data, autoStart), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "auto_start", "false"), - resource.TestCheckResourceAttr(data.ResourceName, "interval_in_seconds", "30"), - resource.TestCheckResourceAttr(data.ResourceName, "source.0.port", "20020"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.env", "test"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_addressUpdate(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - autoStart := "true" - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_basicAddressConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMConnectionMonitor_completeAddressConfig(data, autoStart), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "auto_start", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "interval_in_seconds", "30"), - resource.TestCheckResourceAttr(data.ResourceName, "source.0.port", "20020"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.env", "test"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_vmBasic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_basicVmConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "resource_group_name"), - resource.TestCheckResourceAttr(data.ResourceName, "location", azure.NormalizeLocation(data.Locations.Primary)), - resource.TestCheckResourceAttr(data.ResourceName, "auto_start", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "interval_in_seconds", "60"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_vmComplete(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - autoStart := "false" - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_completeVmConfig(data, autoStart), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "auto_start", "false"), - resource.TestCheckResourceAttr(data.ResourceName, "interval_in_seconds", "30"), - resource.TestCheckResourceAttr(data.ResourceName, "source.0.port", "20020"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.env", "test"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_vmUpdate(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_basicVmConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMConnectionMonitor_completeVmConfig(data, "true"), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "auto_start", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "interval_in_seconds", "30"), - resource.TestCheckResourceAttr(data.ResourceName, "source.0.port", "20020"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.env", "test"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_destinationUpdate(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_basicAddressConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "destination.0.address"), - ), - }, - { - Config: testAccAzureRMConnectionMonitor_basicVmConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "destination.0.virtual_machine_id"), - ), - }, - { - Config: testAccAzureRMConnectionMonitor_basicAddressConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMConnectionMonitorExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "destination.0.address"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMConnectionMonitor_missingDestination(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_missingDestinationConfig(data), - ExpectError: regexp.MustCompile("Error: either `destination.virtual_machine_id` or `destination.address` must be specified"), - }, - }, - }) -} - -func testAccAzureRMConnectionMonitor_conflictingDestinations(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_connection_monitor", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMConnectionMonitorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMConnectionMonitor_conflictingDestinationsConfig(data), - ExpectError: regexp.MustCompile("conflicts with destination.0.address"), - }, - }, - }) -} - -func testCheckAzureRMConnectionMonitorExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Network.ConnectionMonitorsClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - watcherName := rs.Primary.Attributes["network_watcher_name"] - connectionMonitorName := rs.Primary.Attributes["name"] - - resp, err := client.Get(ctx, resourceGroup, watcherName, connectionMonitorName) - if err != nil { - return fmt.Errorf("Bad: Get on connectionMonitorsClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Connection Monitor does not exist: %s", connectionMonitorName) - } - - return nil - } -} - -func testCheckAzureRMConnectionMonitorDestroy(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Network.ConnectionMonitorsClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_connection_monitor" { - continue - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - watcherName := rs.Primary.Attributes["network_watcher_name"] - connectionMonitorName := rs.Primary.Attributes["name"] - - resp, err := client.Get(ctx, resourceGroup, watcherName, connectionMonitorName) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Connection Monitor still exists:%s", *resp.Name) - } - } - - return nil -} - -func testAccAzureRMConnectionMonitor_baseConfig(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_network_watcher" "test" { - name = "acctnw-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "internal" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "src" { - name = "acctni-src%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "src" { - name = "acctvm-src%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.src.id}"] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "osdisk-src%d" - caching = "ReadWrite" - create_option = "FromImage" - managed_disk_type = "Standard_LRS" - } - - os_profile { - computer_name = "hostname%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } -} - -resource "azurerm_virtual_machine_extension" "src" { - name = "network-watcher" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_machine_name = "${azurerm_virtual_machine.src.name}" - publisher = "Microsoft.Azure.NetworkWatcher" - type = "NetworkWatcherAgentLinux" - type_handler_version = "1.4" - auto_upgrade_minor_version = true -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testAccAzureRMConnectionMonitor_baseWithDestConfig(data acceptance.TestData) string { - config := testAccAzureRMConnectionMonitor_baseConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_network_interface" "dest" { - name = "acctni-dest%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "dest" { - name = "acctvm-dest%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.dest.id}"] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "osdisk-dest%d" - caching = "ReadWrite" - create_option = "FromImage" - managed_disk_type = "Standard_LRS" - } - - os_profile { - computer_name = "hostname%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } -} -`, config, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testAccAzureRMConnectionMonitor_basicAddressConfig(data acceptance.TestData) string { - config := testAccAzureRMConnectionMonitor_baseConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "test" { - name = "acctestcm-%d" - network_watcher_name = "${azurerm_network_watcher.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_network_watcher.test.location}" - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - } - - destination { - address = "terraform.io" - port = 80 - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config, data.RandomInteger) -} - -func testAccAzureRMConnectionMonitor_completeAddressConfig(data acceptance.TestData, autoStart string) string { - config := testAccAzureRMConnectionMonitor_baseConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "test" { - name = "acctestcm-%d" - network_watcher_name = "${azurerm_network_watcher.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_network_watcher.test.location}" - - auto_start = %s - interval_in_seconds = 30 - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - port = 20020 - } - - destination { - address = "terraform.io" - port = 443 - } - - tags = { - env = "test" - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config, data.RandomInteger, autoStart) -} - -func testAccAzureRMConnectionMonitor_basicVmConfig(data acceptance.TestData) string { - config := testAccAzureRMConnectionMonitor_baseWithDestConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "test" { - name = "acctestcm-%d" - network_watcher_name = "${azurerm_network_watcher.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_network_watcher.test.location}" - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - } - - destination { - virtual_machine_id = "${azurerm_virtual_machine.dest.id}" - port = 80 - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config, data.RandomInteger) -} - -func testAccAzureRMConnectionMonitor_completeVmConfig(data acceptance.TestData, autoStart string) string { - config := testAccAzureRMConnectionMonitor_baseWithDestConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "test" { - name = "acctestcm-%d" - network_watcher_name = "${azurerm_network_watcher.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_network_watcher.test.location}" - - auto_start = %s - interval_in_seconds = 30 - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - port = 20020 - } - - destination { - virtual_machine_id = "${azurerm_virtual_machine.dest.id}" - port = 443 - } - - tags = { - env = "test" - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config, data.RandomInteger, autoStart) -} - -func testAccAzureRMConnectionMonitor_missingDestinationConfig(data acceptance.TestData) string { - config := testAccAzureRMConnectionMonitor_baseConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "test" { - name = "acctestcm-%d" - network_watcher_name = "${azurerm_network_watcher.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_network_watcher.test.location}" - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - } - - destination { - port = 80 - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config, data.RandomInteger) -} - -func testAccAzureRMConnectionMonitor_conflictingDestinationsConfig(data acceptance.TestData) string { - config := testAccAzureRMConnectionMonitor_baseConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "test" { - name = "acctestcm-%d" - network_watcher_name = "${azurerm_network_watcher.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_network_watcher.test.location}" - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - } - - destination { - address = "terraform.io" - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - port = 80 - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config, data.RandomInteger) -} - -func testAccAzureRMConnectionMonitor_requiresImportConfig(data acceptance.TestData) string { - config := testAccAzureRMConnectionMonitor_basicAddressConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_connection_monitor" "import" { - name = "${azurerm_connection_monitor.test.name}" - network_watcher_name = "${azurerm_connection_monitor.test.network_watcher_name}" - resource_group_name = "${azurerm_connection_monitor.test.resource_group_name}" - location = "${azurerm_connection_monitor.test.location}" - - source { - virtual_machine_id = "${azurerm_virtual_machine.src.id}" - } - - destination { - address = "terraform.io" - port = 80 - } - - depends_on = ["azurerm_virtual_machine_extension.src"] -} -`, config) -} diff --git a/azurerm/internal/services/network/tests/resource_arm_ddos_protection_plan_test.go b/azurerm/internal/services/network/tests/resource_arm_ddos_protection_plan_test.go deleted file mode 100644 index ef8045b066b1..000000000000 --- a/azurerm/internal/services/network/tests/resource_arm_ddos_protection_plan_test.go +++ /dev/null @@ -1,264 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func testAccAzureRMDDoSProtectionPlan_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_ddos_protection_plan", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMDDoSProtectionPlanDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMDDoSProtectionPlan_basicConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMDDoSProtectionPlanExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "virtual_network_ids.#"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMDDoSProtectionPlan_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_ddos_protection_plan", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMDDoSProtectionPlanDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMDDoSProtectionPlan_basicConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMDDoSProtectionPlanExists(data.ResourceName), - ), - }, - { - Config: testAccAzureRMDDoSProtectionPlan_requiresImportConfig(data), - ExpectError: acceptance.RequiresImportError("azurerm_ddos_protection_plan"), - }, - }, - }) -} - -func testAccAzureRMDDoSProtectionPlan_withTags(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_ddos_protection_plan", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMDDoSProtectionPlanDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMDDoSProtectionPlan_withTagsConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMDDoSProtectionPlanExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.environment", "Production"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.cost_center", "MSFT"), - ), - }, - { - Config: testAccAzureRMDDoSProtectionPlan_withUpdatedTagsConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMDDoSProtectionPlanExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.environment", "Staging"), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMDDoSProtectionPlan_disappears(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_ddos_protection_plan", "test") - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMDDoSProtectionPlanDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMDDoSProtectionPlan_basicConfig(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMDDoSProtectionPlanExists(data.ResourceName), - testCheckAzureRMDDoSProtectionPlanDisappears(data.ResourceName), - ), - ExpectNonEmptyPlan: true, - }, - }, - }) -} - -func testCheckAzureRMDDoSProtectionPlanExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Network.DDOSProtectionPlansClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for DDoS Protection Plan: %q", name) - } - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: DDoS Protection Plan %q (Resource Group: %q) does not exist", name, resourceGroup) - } - - return fmt.Errorf("Bad: Get on ddosProtectionPlanClient: %+v", err) - } - - return nil - } -} - -func testCheckAzureRMDDoSProtectionPlanDisappears(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Network.DDOSProtectionPlansClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for DDoS Protection Plan: %q", name) - } - - future, err := client.Delete(ctx, resourceGroup, name) - if err != nil { - return fmt.Errorf("Bad: Delete on ddosProtectionPlanClient: %+v", err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Bad: waiting for Deletion on ddosProtectionPlanClient: %+v", err) - } - - return nil - } -} - -func testCheckAzureRMDDoSProtectionPlanDestroy(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).Network.DDOSProtectionPlansClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_ddos_protection_plan" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return nil - } - - return err - } - - return fmt.Errorf("DDoS Protection Plan still exists:\n%#v", resp.DdosProtectionPlanPropertiesFormat) - } - - return nil -} - -func testAccAzureRMDDoSProtectionPlan_basicConfig(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_ddos_protection_plan" "test" { - name = "acctestddospplan-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) -} - -func testAccAzureRMDDoSProtectionPlan_requiresImportConfig(data acceptance.TestData) string { - basicConfig := testAccAzureRMDDoSProtectionPlan_basicConfig(data) - return fmt.Sprintf(` -%s - -resource "azurerm_ddos_protection_plan" "import" { - name = "${azurerm_ddos_protection_plan.test.name}" - location = "${azurerm_ddos_protection_plan.test.location}" - resource_group_name = "${azurerm_ddos_protection_plan.test.resource_group_name}" -} -`, basicConfig) -} - -func testAccAzureRMDDoSProtectionPlan_withTagsConfig(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_ddos_protection_plan" "test" { - name = "acctestddospplan-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - tags = { - environment = "Production" - cost_center = "MSFT" - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) -} - -func testAccAzureRMDDoSProtectionPlan_withUpdatedTagsConfig(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_ddos_protection_plan" "test" { - name = "acctestddospplan-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - tags = { - environment = "Staging" - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) -} diff --git a/azurerm/internal/services/network/tests/resource_arm_private_link_endpoint_test.go b/azurerm/internal/services/network/tests/resource_arm_private_link_endpoint_test.go deleted file mode 100644 index 60749548ec85..000000000000 --- a/azurerm/internal/services/network/tests/resource_arm_private_link_endpoint_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" -) - -func TestAccAzureRMPrivateLinkEndpoint_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_private_link_endpoint", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMPrivateEndpointDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMPrivateLinkEndpoint_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPrivateEndpointExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "subnet_id"), - ), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMPrivateLinkEndpoint_requestMessage(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_private_link_endpoint", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMPrivateEndpointDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMPrivateLinkEndpoint_requestMessage(data, "CATS: ALL YOUR BASE ARE BELONG TO US."), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPrivateEndpointExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "subnet_id"), - resource.TestCheckResourceAttr(data.ResourceName, "private_service_connection.0.request_message", "CATS: ALL YOUR BASE ARE BELONG TO US."), - ), - }, - data.ImportStep(), - { - Config: testAccAzureRMPrivateLinkEndpoint_requestMessage(data, "CAPTAIN: WHAT YOU SAY!!"), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPrivateEndpointExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "subnet_id"), - resource.TestCheckResourceAttr(data.ResourceName, "private_service_connection.0.request_message", "CAPTAIN: WHAT YOU SAY!!"), - ), - }, - data.ImportStep(), - }, - }) -} - -// The update and complete test cases had to be totally removed since there is a bug with tags and the support for -// tags has been removed, all other attributes are ForceNew. -// API Issue "Unable to remove Tags from Private Link Endpoint": https://github.com/Azure/azure-sdk-for-go/issues/6467 - -func testAccAzureRMPrivateLinkEndpoint_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -%s - -resource "azurerm_private_link_endpoint" "test" { - name = "acctest-privatelink-%d" - resource_group_name = azurerm_resource_group.test.name - location = azurerm_resource_group.test.location - subnet_id = azurerm_subnet.endpoint.id - - private_service_connection { - name = azurerm_private_link_service.test.name - is_manual_connection = false - private_connection_resource_id = azurerm_private_link_service.test.id - } -} -`, testAccAzureRMPrivateEndpointTemplate_template(data, testAccAzureRMPrivateEndpoint_serviceAutoApprove(data)), data.RandomInteger) -} - -func testAccAzureRMPrivateLinkEndpoint_requestMessage(data acceptance.TestData, msg string) string { - return fmt.Sprintf(` -%s - -resource "azurerm_private_link_endpoint" "test" { - name = "acctest-privatelink-%d" - resource_group_name = azurerm_resource_group.test.name - location = azurerm_resource_group.test.location - subnet_id = azurerm_subnet.endpoint.id - - private_service_connection { - name = azurerm_private_link_service.test.name - is_manual_connection = true - private_connection_resource_id = azurerm_private_link_service.test.id - request_message = %q - } -} -`, testAccAzureRMPrivateEndpointTemplate_template(data, testAccAzureRMPrivateEndpoint_serviceManualApprove(data)), data.RandomInteger, msg) -} diff --git a/azurerm/internal/services/network/tests/resource_arm_virtual_network_test.go b/azurerm/internal/services/network/tests/resource_arm_virtual_network_test.go index f146d9492512..48fd8ade8b64 100644 --- a/azurerm/internal/services/network/tests/resource_arm_virtual_network_test.go +++ b/azurerm/internal/services/network/tests/resource_arm_virtual_network_test.go @@ -323,7 +323,7 @@ resource "azurerm_resource_group" "test" { location = "%s" } -resource "azurerm_ddos_protection_plan" "test" { +resource "azurerm_network_ddos_protection_plan" "test" { name = "acctestddospplan-%d" location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" @@ -336,7 +336,7 @@ resource "azurerm_virtual_network" "test" { resource_group_name = "${azurerm_resource_group.test.name}" ddos_protection_plan { - id = "${azurerm_ddos_protection_plan.test.id}" + id = "${azurerm_network_ddos_protection_plan.test.id}" enable = true } diff --git a/azurerm/internal/services/recoveryservices/data_source_recovery_services_protection_policy_vm.go b/azurerm/internal/services/recoveryservices/data_source_backup_policy_vm.go similarity index 72% rename from azurerm/internal/services/recoveryservices/data_source_recovery_services_protection_policy_vm.go rename to azurerm/internal/services/recoveryservices/data_source_backup_policy_vm.go index 401ff7fa38a9..626a073105c9 100644 --- a/azurerm/internal/services/recoveryservices/data_source_recovery_services_protection_policy_vm.go +++ b/azurerm/internal/services/recoveryservices/data_source_backup_policy_vm.go @@ -14,9 +14,9 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func dataSourceArmRecoveryServicesProtectionPolicyVm() *schema.Resource { +func dataSourceArmBackupPolicyVm() *schema.Resource { return &schema.Resource{ - Read: dataSourceArmRecoveryServicesProtectionPolicyVmRead, + Read: dataSourceArmBackupPolicyVmRead, Timeouts: &schema.ResourceTimeout{ Read: schema.DefaultTimeout(5 * time.Minute), @@ -41,7 +41,7 @@ func dataSourceArmRecoveryServicesProtectionPolicyVm() *schema.Resource { } } -func dataSourceArmRecoveryServicesProtectionPolicyVmRead(d *schema.ResourceData, meta interface{}) error { +func dataSourceArmBackupPolicyVmRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).RecoveryServices.ProtectionPoliciesClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -50,15 +50,15 @@ func dataSourceArmRecoveryServicesProtectionPolicyVmRead(d *schema.ResourceData, resourceGroup := d.Get("resource_group_name").(string) vaultName := d.Get("recovery_vault_name").(string) - log.Printf("[DEBUG] Reading Recovery Service Protection Policy %q (resource group %q)", name, resourceGroup) + log.Printf("[DEBUG] Reading Recovery Service Policy %q (resource group %q)", name, resourceGroup) protectionPolicy, err := client.Get(ctx, vaultName, resourceGroup, name) if err != nil { if utils.ResponseWasNotFound(protectionPolicy.Response) { - return fmt.Errorf("Error: Recovery Services Protection Policy %q (Resource Group %q) was not found", name, resourceGroup) + return fmt.Errorf("Error: Backup Policy %q (Resource Group %q) was not found", name, resourceGroup) } - return fmt.Errorf("Error making Read request on Recovery Service Protection Policy %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("Error making Read request on Backup Policy %q (Resource Group %q): %+v", name, resourceGroup, err) } id := strings.Replace(*protectionPolicy.ID, "Subscriptions", "subscriptions", 1) diff --git a/azurerm/internal/services/recoveryservices/registration.go b/azurerm/internal/services/recoveryservices/registration.go index 16724dc1d178..4ad4baf1c1ed 100644 --- a/azurerm/internal/services/recoveryservices/registration.go +++ b/azurerm/internal/services/recoveryservices/registration.go @@ -21,33 +21,25 @@ func (r Registration) WebsiteCategories() []string { // SupportedDataSources returns the supported Data Sources supported by this Service func (r Registration) SupportedDataSources() map[string]*schema.Resource { return map[string]*schema.Resource{ - "azurerm_recovery_services_vault": dataSourceArmRecoveryServicesVault(), - "azurerm_recovery_services_protection_policy_vm": dataSourceArmRecoveryServicesProtectionPolicyVm(), + "azurerm_recovery_services_vault": dataSourceArmRecoveryServicesVault(), + "azurerm_backup_policy_vm": dataSourceArmBackupPolicyVm(), } } // SupportedResources returns the supported Resources supported by this Service func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ - "azurerm_backup_container_storage_account": resourceArmBackupProtectionContainerStorageAccount(), - "azurerm_backup_policy_file_share": resourceArmBackupProtectionPolicyFileShare(), - "azurerm_backup_protected_file_share": resourceArmBackupProtectedFileShare(), - "azurerm_backup_protected_vm": resourceArmRecoveryServicesBackupProtectedVM(), - "azurerm_backup_policy_vm": resourceArmBackupProtectionPolicyVM(), - "azurerm_recovery_network_mapping": resourceArmRecoveryServicesNetworkMapping(), - "azurerm_recovery_replicated_vm": resourceArmRecoveryServicesReplicatedVm(), - "azurerm_recovery_services_fabric": resourceArmRecoveryServicesFabric(), - "azurerm_recovery_services_protected_vm": resourceArmRecoveryServicesProtectedVm(), - "azurerm_recovery_services_protection_container": resourceArmRecoveryServicesProtectionContainer(), - "azurerm_recovery_services_protection_container_mapping": resourceArmRecoveryServicesProtectionContainerMapping(), - "azurerm_recovery_services_protection_policy_vm": resourceArmRecoveryServicesProtectionPolicyVm(), - "azurerm_recovery_services_replication_policy": resourceArmRecoveryServicesReplicationPolicy(), - "azurerm_recovery_services_vault": resourceArmRecoveryServicesVault(), - "azurerm_site_recovery_fabric": resourceArmSiteRecoveryFabric(), - "azurerm_site_recovery_network_mapping": resourceArmSiteRecoveryNetworkMapping(), - "azurerm_site_recovery_protection_container": resourceArmSiteRecoveryProtectionContainer(), - "azurerm_site_recovery_protection_container_mapping": resourceArmSiteRecoveryProtectionContainerMapping(), - "azurerm_site_recovery_replicated_vm": resourceArmSiteRecoveryReplicatedVM(), - "azurerm_site_recovery_replication_policy": resourceArmSiteRecoveryReplicationPolicy(), + "azurerm_backup_container_storage_account": resourceArmBackupProtectionContainerStorageAccount(), + "azurerm_backup_policy_file_share": resourceArmBackupProtectionPolicyFileShare(), + "azurerm_backup_protected_file_share": resourceArmBackupProtectedFileShare(), + "azurerm_backup_protected_vm": resourceArmRecoveryServicesBackupProtectedVM(), + "azurerm_backup_policy_vm": resourceArmBackupProtectionPolicyVM(), + "azurerm_recovery_services_vault": resourceArmRecoveryServicesVault(), + "azurerm_site_recovery_fabric": resourceArmSiteRecoveryFabric(), + "azurerm_site_recovery_network_mapping": resourceArmSiteRecoveryNetworkMapping(), + "azurerm_site_recovery_protection_container": resourceArmSiteRecoveryProtectionContainer(), + "azurerm_site_recovery_protection_container_mapping": resourceArmSiteRecoveryProtectionContainerMapping(), + "azurerm_site_recovery_replicated_vm": resourceArmSiteRecoveryReplicatedVM(), + "azurerm_site_recovery_replication_policy": resourceArmSiteRecoveryReplicationPolicy(), } } diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_fabric.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_fabric.go deleted file mode 100644 index bb0d6e00b0b8..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_fabric.go +++ /dev/null @@ -1,164 +0,0 @@ -package recoveryservices - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2018-01-10/siterecovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesFabric() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_services_fabric` resource is deprecated in favor of `azurerm_site_recovery_fabric` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryServicesFabricCreate, - Read: resourceArmRecoveryServicesFabricRead, - Update: nil, - Delete: resourceArmRecoveryServicesFabricDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - "location": azure.SchemaLocation(), - }, - } -} - -func resourceArmRecoveryServicesFabricCreate(d *schema.ResourceData, meta interface{}) error { - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - location := azure.NormalizeLocation(d.Get("location").(string)) - name := d.Get("name").(string) - - client := meta.(*clients.Client).RecoveryServices.FabricClient(resGroup, vaultName) - ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) - defer cancel() - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing rec overy services fabric %s (vault %s): %+v", name, vaultName, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_resource_group", azure.HandleAzureSdkForGoBug2824(*existing.ID)) - } - } - - parameters := siterecovery.FabricCreationInput{ - Properties: &siterecovery.FabricCreationInputProperties{ - CustomDetails: siterecovery.AzureFabricCreationInput{ - InstanceType: "Azure", - Location: &location, - }, - }, - } - - future, err := client.Create(ctx, name, parameters) - if err != nil { - return fmt.Errorf("Error creating recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error creating recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - - resp, err := client.Get(ctx, name) - if err != nil { - return fmt.Errorf("Error retrieving recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryServicesFabricRead(d, meta) -} - -func resourceArmRecoveryServicesFabricRead(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - name := id.Path["replicationFabrics"] - - client := meta.(*clients.Client).RecoveryServices.FabricClient(resGroup, vaultName) - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resp, err := client.Get(ctx, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making Read request on recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - - d.Set("name", resp.Name) - d.Set("resource_group_name", resGroup) - if props := resp.Properties; props != nil { - if azureDetails, isAzureDetails := props.CustomDetails.AsAzureFabricSpecificDetails(); isAzureDetails { - d.Set("location", azureDetails.Location) - } - } - d.Set("recovery_vault_name", vaultName) - return nil -} - -func resourceArmRecoveryServicesFabricDelete(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - name := id.Path["replicationFabrics"] - - client := meta.(*clients.Client).RecoveryServices.FabricClient(resGroup, vaultName) - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - future, err := client.Delete(ctx, name) - if err != nil { - return fmt.Errorf("Error deleting recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_network_mapping.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_network_mapping.go deleted file mode 100644 index fc6a4d24a3ba..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_network_mapping.go +++ /dev/null @@ -1,216 +0,0 @@ -package recoveryservices - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2018-01-10/siterecovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesNetworkMapping() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_network_mapping` resource is deprecated in favor of `azurerm_site_recovery_network_mapping` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryNetworkMappingCreate, - Read: resourceArmRecoveryNetworkMappingRead, - Delete: resourceArmRecoveryNetworkMappingDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - "source_recovery_fabric_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "target_recovery_fabric_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "source_network_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_network_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - }, - } -} - -func resourceArmRecoveryNetworkMappingCreate(d *schema.ResourceData, meta interface{}) error { - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - fabricName := d.Get("source_recovery_fabric_name").(string) - targetFabricName := d.Get("target_recovery_fabric_name").(string) - sourceNetworkId := d.Get("source_network_id").(string) - targetNetworkId := d.Get("target_network_id").(string) - name := d.Get("name").(string) - - client := meta.(*clients.Client).RecoveryServices.NetworkMappingClient(resGroup, vaultName) - ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) - defer cancel() - - //get network name from id - parsedSourceNetworkId, err := azure.ParseAzureResourceID(sourceNetworkId) - if err != nil { - return fmt.Errorf("[ERROR] Unable to parse source_network_id '%s' (network mapping %s): %+v", sourceNetworkId, name, err) - } - sourceNetworkName, hasName := parsedSourceNetworkId.Path["virtualNetworks"] - if !hasName { - sourceNetworkName, hasName = parsedSourceNetworkId.Path["virtualnetworks"] // Handle that different APIs return different ID casings - if !hasName { - return fmt.Errorf("[ERROR] parsed source_network_id '%s' doesn't contain 'virtualnetworks'", parsedSourceNetworkId) - } - } - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, fabricName, sourceNetworkName, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing recovery services fabric %s (vault %s): %+v", name, vaultName, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_network_mapping", azure.HandleAzureSdkForGoBug2824(*existing.ID)) - } - } - - var parameters = siterecovery.CreateNetworkMappingInput{ - Properties: &siterecovery.CreateNetworkMappingInputProperties{ - RecoveryNetworkID: &targetNetworkId, - RecoveryFabricName: &targetFabricName, - FabricSpecificDetails: siterecovery.AzureToAzureCreateNetworkMappingInput{ - PrimaryNetworkID: &sourceNetworkId, - }, - }, - } - future, err := client.Create(ctx, fabricName, sourceNetworkName, name, parameters) - if err != nil { - return fmt.Errorf("Error creating recovery network mapping %s (vault %s): %+v", name, vaultName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error creating recovery network mapping %s (vault %s): %+v", name, vaultName, err) - } - - resp, err := client.Get(ctx, fabricName, sourceNetworkName, name) - if err != nil { - return fmt.Errorf("Error retrieving recovery network mapping %s (vault %s): %+v", name, vaultName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryNetworkMappingRead(d, meta) -} - -func resourceArmRecoveryNetworkMappingRead(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - networkName := id.Path["replicationNetworks"] - name := id.Path["replicationNetworkMappings"] - - client := meta.(*clients.Client).RecoveryServices.NetworkMappingClient(resGroup, vaultName) - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resp, err := client.Get(ctx, fabricName, networkName, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making Read request on recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - d.Set("resource_group_name", resGroup) - d.Set("recovery_vault_name", vaultName) - d.Set("source_recovery_fabric_name", fabricName) - d.Set("name", resp.Name) - if props := resp.Properties; props != nil { - d.Set("source_network_id", props.PrimaryNetworkID) - d.Set("target_network_id", props.RecoveryNetworkID) - - targetFabricId, err := azure.ParseAzureResourceID(azure.HandleAzureSdkForGoBug2824(*resp.Properties.RecoveryFabricArmID)) - if err != nil { - return err - } - d.Set("target_recovery_fabric_name", targetFabricId.Path["replicationFabrics"]) - } - - return nil -} - -func resourceArmRecoveryNetworkMappingDelete(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - networkName := id.Path["replicationNetworks"] - name := id.Path["replicationNetworkMappings"] - - client := meta.(*clients.Client).RecoveryServices.NetworkMappingClient(resGroup, vaultName) - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - future, err := client.Delete(ctx, fabricName, networkName, name) - if err != nil { - return fmt.Errorf("Error deleting recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protected_vm.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protected_vm.go deleted file mode 100644 index 68181b97366c..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protected_vm.go +++ /dev/null @@ -1,283 +0,0 @@ -package recoveryservices - -import ( - "context" - "fmt" - "log" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2019-05-13/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesProtectedVm() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_services_protected_vm` resource is deprecated in favor of `azurerm_backup_protected_vm` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryServicesProtectedVmCreateUpdate, - Read: resourceArmRecoveryServicesProtectedVmRead, - Update: resourceArmRecoveryServicesProtectedVmCreateUpdate, - Delete: resourceArmRecoveryServicesProtectedVmDelete, - - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(80 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(80 * time.Minute), - Delete: schema.DefaultTimeout(80 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - - "source_vm_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - }, - - "backup_policy_id": { - Type: schema.TypeString, - Required: true, - ValidateFunc: azure.ValidateResourceID, - }, - - "tags": tags.Schema(), - }, - } -} - -func resourceArmRecoveryServicesProtectedVmCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).RecoveryServices.ProtectedItemsClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - resourceGroup := d.Get("resource_group_name").(string) - t := d.Get("tags").(map[string]interface{}) - - vaultName := d.Get("recovery_vault_name").(string) - vmId := d.Get("source_vm_id").(string) - policyId := d.Get("backup_policy_id").(string) - - //get VM name from id - parsedVmId, err := azure.ParseAzureResourceID(vmId) - if err != nil { - return fmt.Errorf("[ERROR] Unable to parse source_vm_id '%s': %+v", vmId, err) - } - vmName, hasName := parsedVmId.Path["virtualMachines"] - if !hasName { - return fmt.Errorf("[ERROR] parsed source_vm_id '%s' doesn't contain 'virtualMachines'", vmId) - } - - protectedItemName := fmt.Sprintf("VM;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroup, vmName) - containerName := fmt.Sprintf("iaasvmcontainer;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroup, vmName) - - log.Printf("[DEBUG] Creating/updating Recovery Service Protected VM %s (resource group %q)", protectedItemName, resourceGroup) - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err2 := client.Get(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName, "") - if err2 != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing Recovery Service Protected VM %q (Resource Group %q): %+v", protectedItemName, resourceGroup, err2) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_services_protected_vm", *existing.ID) - } - } - - item := backup.ProtectedItemResource{ - Tags: tags.Expand(t), - Properties: &backup.AzureIaaSComputeVMProtectedItem{ - PolicyID: &policyId, - ProtectedItemType: backup.ProtectedItemTypeMicrosoftClassicComputevirtualMachines, - WorkloadType: backup.DataSourceTypeVM, - SourceResourceID: utils.String(vmId), - FriendlyName: utils.String(vmName), - VirtualMachineID: utils.String(vmId), - }, - } - - if _, err = client.CreateOrUpdate(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName, item); err != nil { - return fmt.Errorf("Error creating/updating Recovery Service Protected VM %q (Resource Group %q): %+v", protectedItemName, resourceGroup, err) - } - - resp, err := resourceArmRecoveryServicesProtectedVmWaitForStateCreateUpdate(ctx, client, vaultName, resourceGroup, containerName, protectedItemName, policyId, d) - if err != nil { - return err - } - - id := strings.Replace(*resp.ID, "Subscriptions", "subscriptions", 1) // This code is a workaround for this bug https://github.com/Azure/azure-sdk-for-go/issues/2824 - d.SetId(id) - - return resourceArmRecoveryServicesProtectedVmRead(d, meta) -} - -func resourceArmRecoveryServicesProtectedVmRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).RecoveryServices.ProtectedItemsClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - protectedItemName := id.Path["protectedItems"] - vaultName := id.Path["vaults"] - resourceGroup := id.ResourceGroup - containerName := id.Path["protectionContainers"] - - log.Printf("[DEBUG] Reading Recovery Service Protected VM %q (resource group %q)", protectedItemName, resourceGroup) - - resp, err := client.Get(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName, "") - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - - return fmt.Errorf("Error making Read request on Recovery Service Protected VM %q (Resource Group %q): %+v", protectedItemName, resourceGroup, err) - } - - d.Set("resource_group_name", resourceGroup) - d.Set("recovery_vault_name", vaultName) - - if properties := resp.Properties; properties != nil { - if vm, ok := properties.AsAzureIaaSComputeVMProtectedItem(); ok { - d.Set("source_vm_id", vm.SourceResourceID) - - if v := vm.PolicyID; v != nil { - d.Set("backup_policy_id", strings.Replace(*v, "Subscriptions", "subscriptions", 1)) - } - } - } - - return tags.FlattenAndSet(d, resp.Tags) -} - -func resourceArmRecoveryServicesProtectedVmDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).RecoveryServices.ProtectedItemsClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - protectedItemName := id.Path["protectedItems"] - resourceGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - containerName := id.Path["protectionContainers"] - - log.Printf("[DEBUG] Deleting Recovery Service Protected Item %q (resource group %q)", protectedItemName, resourceGroup) - - resp, err := client.Delete(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName) - if err != nil { - if !utils.ResponseWasNotFound(resp) { - return fmt.Errorf("Error issuing delete request for Recovery Service Protected VM %q (Resource Group %q): %+v", protectedItemName, resourceGroup, err) - } - } - - if _, err := resourceArmRecoveryServicesProtectedVmWaitForDeletion(ctx, client, vaultName, resourceGroup, containerName, protectedItemName, "", d); err != nil { - return err - } - - return nil -} - -func resourceArmRecoveryServicesProtectedVmWaitForStateCreateUpdate(ctx context.Context, client *backup.ProtectedItemsClient, vaultName, resourceGroup, containerName, protectedItemName string, policyId string, d *schema.ResourceData) (backup.ProtectedItemResource, error) { - state := &resource.StateChangeConf{ - MinTimeout: 30 * time.Second, - Delay: 10 * time.Second, - Pending: []string{"NotFound"}, - Target: []string{"Found"}, - Refresh: resourceArmRecoveryServicesProtectedVmRefreshFunc(ctx, client, vaultName, resourceGroup, containerName, protectedItemName, policyId, true), - } - - if d.IsNewResource() { - state.Timeout = d.Timeout(schema.TimeoutCreate) - } else { - state.Timeout = d.Timeout(schema.TimeoutUpdate) - } - - resp, err := state.WaitForState() - if err != nil { - i, _ := resp.(backup.ProtectedItemResource) - return i, fmt.Errorf("Error waiting for the Recovery Service Protected VM %q to be true (Resource Group %q) to provision: %+v", protectedItemName, resourceGroup, err) - } - - return resp.(backup.ProtectedItemResource), nil -} - -func resourceArmRecoveryServicesProtectedVmWaitForDeletion(ctx context.Context, client *backup.ProtectedItemsClient, vaultName, resourceGroup, containerName, protectedItemName string, policyId string, d *schema.ResourceData) (backup.ProtectedItemResource, error) { - state := &resource.StateChangeConf{ - MinTimeout: 30 * time.Second, - Delay: 10 * time.Second, - Pending: []string{"Found"}, - Target: []string{"NotFound"}, - Refresh: resourceArmRecoveryServicesProtectedVmRefreshFunc(ctx, client, vaultName, resourceGroup, containerName, protectedItemName, policyId, false), - Timeout: d.Timeout(schema.TimeoutDelete), - } - - resp, err := state.WaitForState() - if err != nil { - i, _ := resp.(backup.ProtectedItemResource) - return i, fmt.Errorf("Error waiting for the Recovery Service Protected VM %q to be false (Resource Group %q) to provision: %+v", protectedItemName, resourceGroup, err) - } - - return resp.(backup.ProtectedItemResource), nil -} - -func resourceArmRecoveryServicesProtectedVmRefreshFunc(ctx context.Context, client *backup.ProtectedItemsClient, vaultName, resourceGroup, containerName, protectedItemName string, policyId string, newResource bool) resource.StateRefreshFunc { - // TODO: split this into two functions - return func() (interface{}, string, error) { - resp, err := client.Get(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName, "") - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return resp, "NotFound", nil - } - - return resp, "Error", fmt.Errorf("Error making Read request on Recovery Service Protected VM %q (Resource Group %q): %+v", protectedItemName, resourceGroup, err) - } else if !newResource && policyId != "" { - if properties := resp.Properties; properties != nil { - if vm, ok := properties.AsAzureIaaSComputeVMProtectedItem(); ok { - if v := vm.PolicyID; v != nil { - if strings.Replace(*v, "Subscriptions", "subscriptions", 1) != policyId { - return resp, "NotFound", nil - } - } else { - return resp, "Error", fmt.Errorf("Error reading policy ID attribute nil on Recovery Service Protected VM %q (Resource Group %q)", protectedItemName, resourceGroup) - } - } else { - return resp, "Error", fmt.Errorf("Error reading properties on Recovery Service Protected VM %q (Resource Group %q)", protectedItemName, resourceGroup) - } - } else { - return resp, "Error", fmt.Errorf("Error reading properties on empty Recovery Service Protected VM %q (Resource Group %q)", protectedItemName, resourceGroup) - } - } - return resp, "Found", nil - } -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container.go deleted file mode 100644 index f31bbd4c1626..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container.go +++ /dev/null @@ -1,162 +0,0 @@ -package recoveryservices - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2018-01-10/siterecovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesProtectionContainer() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_services_protection_container` resource is deprecated in favor of `azurerm_site_recovery_protection_container` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryServicesProtectionContainerCreate, - Read: resourceArmRecoveryServicesProtectionContainerRead, - Update: nil, - Delete: resourceArmRecoveryServicesProtectionContainerDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - "recovery_fabric_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - }, - } -} - -func resourceArmRecoveryServicesProtectionContainerCreate(d *schema.ResourceData, meta interface{}) error { - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - fabricName := d.Get("recovery_fabric_name").(string) - name := d.Get("name").(string) - - client := meta.(*clients.Client).RecoveryServices.ProtectionContainerClient(resGroup, vaultName) - ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) - defer cancel() - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, fabricName, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing recovery services protection container %s (fabric %s): %+v", name, fabricName, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_services_protection_container", azure.HandleAzureSdkForGoBug2824(*existing.ID)) - } - } - - parameters := siterecovery.CreateProtectionContainerInput{ - Properties: &siterecovery.CreateProtectionContainerInputProperties{}, - } - - future, err := client.Create(ctx, fabricName, name, parameters) - if err != nil { - return fmt.Errorf("Error creating recovery services protection container %s (fabric %s): %+v", name, fabricName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error creating recovery services protection container %s (fabric %s): %+v", name, fabricName, err) - } - - resp, err := client.Get(ctx, fabricName, name) - if err != nil { - return fmt.Errorf("Error retrieving site recovery protection container %s (fabric %s): %+v", name, fabricName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryServicesProtectionContainerRead(d, meta) -} - -func resourceArmRecoveryServicesProtectionContainerRead(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - name := id.Path["replicationProtectionContainers"] - - client := meta.(*clients.Client).RecoveryServices.ProtectionContainerClient(resGroup, vaultName) - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resp, err := client.Get(ctx, fabricName, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making Read request on recovery services protection container %s (fabric %s): %+v", name, fabricName, err) - } - - d.Set("name", resp.Name) - d.Set("resource_group_name", resGroup) - d.Set("recovery_vault_name", vaultName) - d.Set("recovery_fabric_name", fabricName) - return nil -} - -func resourceArmRecoveryServicesProtectionContainerDelete(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - name := id.Path["replicationProtectionContainers"] - - client := meta.(*clients.Client).RecoveryServices.ProtectionContainerClient(resGroup, vaultName) - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - future, err := client.Delete(ctx, fabricName, name) - if err != nil { - return fmt.Errorf("Error deleting recovery services protection container %s (fabric %s): %+v", name, fabricName, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of recovery services protection container %s (fabric %s): %+v", name, fabricName, err) - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container_mapping.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container_mapping.go deleted file mode 100644 index cbeea35521bf..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_container_mapping.go +++ /dev/null @@ -1,203 +0,0 @@ -package recoveryservices - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2018-01-10/siterecovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesProtectionContainerMapping() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_services_protection_container_mapping` resource is deprecated in favor of `azurerm_site_recovery_protection_container_mapping` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryServicesContainerMappingCreate, - Read: resourceArmRecoveryServicesContainerMappingRead, - Update: nil, - Delete: resourceArmRecoveryServicesContainerMappingDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - "recovery_fabric_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "recovery_replication_policy_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "recovery_source_protection_container_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "recovery_target_protection_container_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - }, - } -} - -func resourceArmRecoveryServicesContainerMappingCreate(d *schema.ResourceData, meta interface{}) error { - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - fabricName := d.Get("recovery_fabric_name").(string) - policyId := d.Get("recovery_replication_policy_id").(string) - protectionContainerName := d.Get("recovery_source_protection_container_name").(string) - targetContainerId := d.Get("recovery_target_protection_container_id").(string) - name := d.Get("name").(string) - - client := meta.(*clients.Client).RecoveryServices.ContainerMappingClient(resGroup, vaultName) - ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) - defer cancel() - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, fabricName, protectionContainerName, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing recovery services protection container mapping %s (fabric %s, container %s): %+v", name, fabricName, protectionContainerName, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_services_protection_container_mapping", azure.HandleAzureSdkForGoBug2824(*existing.ID)) - } - } - - var parameters = siterecovery.CreateProtectionContainerMappingInput{ - Properties: &siterecovery.CreateProtectionContainerMappingInputProperties{ - TargetProtectionContainerID: &targetContainerId, - PolicyID: &policyId, - ProviderSpecificInput: siterecovery.ReplicationProviderSpecificContainerMappingInput{}, - }, - } - future, err := client.Create(ctx, fabricName, protectionContainerName, name, parameters) - if err != nil { - return fmt.Errorf("Error creating recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error creating recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - resp, err := client.Get(ctx, fabricName, protectionContainerName, name) - if err != nil { - return fmt.Errorf("Error retrieving site recovery protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryServicesContainerMappingRead(d, meta) -} - -func resourceArmRecoveryServicesContainerMappingRead(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - protectionContainerName := id.Path["replicationProtectionContainers"] - name := id.Path["replicationProtectionContainerMappings"] - - client := meta.(*clients.Client).RecoveryServices.ContainerMappingClient(resGroup, vaultName) - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resp, err := client.Get(ctx, fabricName, protectionContainerName, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making Read request on recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - d.Set("resource_group_name", resGroup) - d.Set("recovery_vault_name", vaultName) - d.Set("recovery_fabric_name", fabricName) - d.Set("recovery_source_protection_container_name", resp.Properties.SourceProtectionContainerFriendlyName) - d.Set("name", resp.Name) - d.Set("recovery_replication_policy_id", resp.Properties.PolicyID) - d.Set("recovery_target_protection_container_id", resp.Properties.TargetProtectionContainerID) - return nil -} - -func resourceArmRecoveryServicesContainerMappingDelete(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - protectionContainerName := id.Path["replicationProtectionContainers"] - name := id.Path["replicationProtectionContainerMappings"] - instanceType := string(siterecovery.InstanceTypeBasicReplicationProviderSpecificContainerMappingInputInstanceTypeA2A) - - client := meta.(*clients.Client).RecoveryServices.ContainerMappingClient(resGroup, vaultName) - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - input := siterecovery.RemoveProtectionContainerMappingInput{ - Properties: &siterecovery.RemoveProtectionContainerMappingInputProperties{ - ProviderSpecificInput: &siterecovery.ReplicationProviderContainerUnmappingInput{ - InstanceType: &instanceType, - }, - }, - } - - future, err := client.Delete(ctx, fabricName, protectionContainerName, name, input) - if err != nil { - return fmt.Errorf("Error deleting recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of recovery services protection container mapping %s (vault %s): %+v", name, vaultName, err) - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_policy_vm.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_policy_vm.go deleted file mode 100644 index 9239c1d79349..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_protection_policy_vm.go +++ /dev/null @@ -1,764 +0,0 @@ -package recoveryservices - -import ( - "context" - "fmt" - "log" - "regexp" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2019-05-13/backup" - "github.com/Azure/go-autorest/autorest/date" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/set" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesProtectionPolicyVm() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_services_protection_policy_vm` resource is deprecated in favor of `azurerm_backup_policy_vm` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryServicesProtectionPolicyVmCreateUpdate, - Read: resourceArmRecoveryServicesProtectionPolicyVmRead, - Update: resourceArmRecoveryServicesProtectionPolicyVmCreateUpdate, - Delete: resourceArmRecoveryServicesProtectionPolicyVmDelete, - - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^[a-zA-Z][-_!a-zA-Z0-9]{2,149}$"), - "Backup Policy name must be 3 - 150 characters long, start with a letter, contain only letters and numbers.", - ), - }, - - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - - "timezone": { - Type: schema.TypeString, - Optional: true, - Default: "UTC", - }, - - "backup": { - Type: schema.TypeList, - MaxItems: 1, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - - "frequency": { - Type: schema.TypeString, - Required: true, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(backup.ScheduleRunTypeDaily), - string(backup.ScheduleRunTypeWeekly), - }, true), - }, - - "time": { //applies to all backup schedules & retention times (they all must be the same) - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^([01][0-9]|[2][0-3]):([03][0])$"), //time must be on the hour or half past - "Time of day must match the format HH:mm where HH is 00-23 and mm is 00 or 30", - ), - }, - - "weekdays": { //only for weekly - Type: schema.TypeSet, - Optional: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validate.DayOfTheWeek(true), - }, - }, - }, - }, - }, - - "retention_daily": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "count": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(1, 9999), - }, - }, - }, - }, - - "retention_weekly": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "count": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(1, 9999), - }, - - "weekdays": { - Type: schema.TypeSet, - Required: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validate.DayOfTheWeek(true), - }, - }, - }, - }, - }, - - "retention_monthly": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "count": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(1, 9999), - }, - - "weeks": { - Type: schema.TypeSet, - Required: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(backup.WeekOfMonthFirst), - string(backup.WeekOfMonthSecond), - string(backup.WeekOfMonthThird), - string(backup.WeekOfMonthFourth), - string(backup.WeekOfMonthLast), - }, true), - }, - }, - - "weekdays": { - Type: schema.TypeSet, - Required: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validate.DayOfTheWeek(true), - }, - }, - }, - }, - }, - - "retention_yearly": { - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "count": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(1, 9999), - }, - - "months": { - Type: schema.TypeSet, - Required: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validate.Month(true), - }, - }, - - "weeks": { - Type: schema.TypeSet, - Required: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validation.StringInSlice([]string{ - string(backup.WeekOfMonthFirst), - string(backup.WeekOfMonthSecond), - string(backup.WeekOfMonthThird), - string(backup.WeekOfMonthFourth), - string(backup.WeekOfMonthLast), - }, true), - }, - }, - - "weekdays": { - Type: schema.TypeSet, - Required: true, - Set: set.HashStringIgnoreCase, - Elem: &schema.Schema{ - Type: schema.TypeString, - DiffSuppressFunc: suppress.CaseDifference, - ValidateFunc: validate.DayOfTheWeek(true), - }, - }, - }, - }, - }, - - "tags": tags.Schema(), - }, - - //if daily, we need daily retention - //if weekly daily cannot be set, and we need weekly - CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { - _, hasDaily := diff.GetOk("retention_daily") - _, hasWeekly := diff.GetOk("retention_weekly") - - frequencyI, _ := diff.GetOk("backup.0.frequency") - frequency := strings.ToLower(frequencyI.(string)) - if frequency == "daily" { - if !hasDaily { - return fmt.Errorf("`retention_daily` must be set when backup.0.frequency is daily") - } - - if _, ok := diff.GetOk("backup.0.weekdays"); ok { - return fmt.Errorf("`backup.0.weekdays` should be not set when backup.0.frequency is daily") - } - } else if frequency == "weekly" { - if hasDaily { - return fmt.Errorf("`retention_daily` must be not set when backup.0.frequency is weekly") - } - if !hasWeekly { - return fmt.Errorf("`retention_weekly` must be set when backup.0.frequency is weekly") - } - } else { - return fmt.Errorf("Unrecognized value for backup.0.frequency") - } - - return nil - }, - } -} - -func resourceArmRecoveryServicesProtectionPolicyVmCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).RecoveryServices.ProtectionPoliciesClient - ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - policyName := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - t := d.Get("tags").(map[string]interface{}) - - log.Printf("[DEBUG] Creating/updating Recovery Service Protection Policy %s (resource group %q)", policyName, resourceGroup) - - //getting this ready now because its shared between *everything*, time is... complicated for this resource - timeOfDay := d.Get("backup.0.time").(string) - dateOfDay, err := time.Parse(time.RFC3339, fmt.Sprintf("2018-07-30T%s:00Z", timeOfDay)) - if err != nil { - return fmt.Errorf("Error generating time from %q for policy %q (Resource Group %q): %+v", timeOfDay, policyName, resourceGroup, err) - } - times := append(make([]date.Time, 0), date.Time{Time: dateOfDay}) - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err2 := client.Get(ctx, vaultName, resourceGroup, policyName) - if err2 != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing Recovery Service Protection Policy %q (Resource Group %q): %+v", policyName, resourceGroup, err2) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_services_protection_policy_vm", *existing.ID) - } - } - - policy := backup.ProtectionPolicyResource{ - Tags: tags.Expand(t), - Properties: &backup.AzureIaaSVMProtectionPolicy{ - TimeZone: utils.String(d.Get("timezone").(string)), - BackupManagementType: backup.BackupManagementTypeAzureIaasVM, - SchedulePolicy: expandArmRecoveryServicesProtectionPolicySchedule(d, times), - RetentionPolicy: &backup.LongTermRetentionPolicy{ //SimpleRetentionPolicy only has duration property ¯\_(ツ)_/¯ - RetentionPolicyType: backup.RetentionPolicyTypeLongTermRetentionPolicy, - DailySchedule: expandArmRecoveryServicesProtectionPolicyRetentionDaily(d, times), - WeeklySchedule: expandArmRecoveryServicesProtectionPolicyRetentionWeekly(d, times), - MonthlySchedule: expandArmRecoveryServicesProtectionPolicyRetentionMonthly(d, times), - YearlySchedule: expandArmRecoveryServicesProtectionPolicyRetentionYearly(d, times), - }, - }, - } - if _, err = client.CreateOrUpdate(ctx, vaultName, resourceGroup, policyName, policy); err != nil { - return fmt.Errorf("Error creating/updating Recovery Service Protection Policy %q (Resource Group %q): %+v", policyName, resourceGroup, err) - } - - resp, err := resourceArmRecoveryServicesProtectionPolicyWaitForUpdate(ctx, client, vaultName, resourceGroup, policyName, d) - if err != nil { - return err - } - - id := strings.Replace(*resp.ID, "Subscriptions", "subscriptions", 1) - d.SetId(id) - - return resourceArmRecoveryServicesProtectionPolicyVmRead(d, meta) -} - -func resourceArmRecoveryServicesProtectionPolicyVmRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).RecoveryServices.ProtectionPoliciesClient - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - policyName := id.Path["backupPolicies"] - vaultName := id.Path["vaults"] - resourceGroup := id.ResourceGroup - - log.Printf("[DEBUG] Reading Recovery Service Protection Policy %q (resource group %q)", policyName, resourceGroup) - - resp, err := client.Get(ctx, vaultName, resourceGroup, policyName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - - return fmt.Errorf("Error making Read request on Recovery Service Protection Policy %q (Resource Group %q): %+v", policyName, resourceGroup, err) - } - - d.Set("name", policyName) - d.Set("resource_group_name", resourceGroup) - d.Set("recovery_vault_name", vaultName) - - if properties, ok := resp.Properties.AsAzureIaaSVMProtectionPolicy(); ok && properties != nil { - d.Set("timezone", properties.TimeZone) - - if schedule, ok := properties.SchedulePolicy.AsSimpleSchedulePolicy(); ok && schedule != nil { - if err := d.Set("backup", flattenArmRecoveryServicesProtectionPolicySchedule(schedule)); err != nil { - return fmt.Errorf("Error setting `backup`: %+v", err) - } - } - - if retention, ok := properties.RetentionPolicy.AsLongTermRetentionPolicy(); ok && retention != nil { - if s := retention.DailySchedule; s != nil { - if err := d.Set("retention_daily", flattenArmRecoveryServicesProtectionPolicyRetentionDaily(s)); err != nil { - return fmt.Errorf("Error setting `retention_daily`: %+v", err) - } - } else { - d.Set("retention_daily", nil) - } - - if s := retention.WeeklySchedule; s != nil { - if err := d.Set("retention_weekly", flattenArmRecoveryServicesProtectionPolicyRetentionWeekly(s)); err != nil { - return fmt.Errorf("Error setting `retention_weekly`: %+v", err) - } - } else { - d.Set("retention_weekly", nil) - } - - if s := retention.MonthlySchedule; s != nil { - if err := d.Set("retention_monthly", flattenArmRecoveryServicesProtectionPolicyRetentionMonthly(s)); err != nil { - return fmt.Errorf("Error setting `retention_monthly`: %+v", err) - } - } else { - d.Set("retention_monthly", nil) - } - - if s := retention.YearlySchedule; s != nil { - if err := d.Set("retention_yearly", flattenArmRecoveryServicesProtectionPolicyRetentionYearly(s)); err != nil { - return fmt.Errorf("Error setting `retention_yearly`: %+v", err) - } - } else { - d.Set("retention_yearly", nil) - } - } - } - - return tags.FlattenAndSet(d, resp.Tags) -} - -func resourceArmRecoveryServicesProtectionPolicyVmDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).RecoveryServices.ProtectionPoliciesClient - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - policyName := id.Path["backupPolicies"] - resourceGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - - log.Printf("[DEBUG] Deleting Recovery Service Protected Item %q (resource group %q)", policyName, resourceGroup) - - resp, err := client.Delete(ctx, vaultName, resourceGroup, policyName) - if err != nil { - if !utils.ResponseWasNotFound(resp) { - return fmt.Errorf("Error issuing delete request for Recovery Service Protection Policy %q (Resource Group %q): %+v", policyName, resourceGroup, err) - } - } - - if _, err := resourceArmRecoveryServicesProtectionPolicyWaitForDeletion(ctx, client, vaultName, resourceGroup, policyName, d); err != nil { - return err - } - - return nil -} - -func expandArmRecoveryServicesProtectionPolicySchedule(d *schema.ResourceData, times []date.Time) *backup.SimpleSchedulePolicy { - if bb, ok := d.Get("backup").([]interface{}); ok && len(bb) > 0 { - block := bb[0].(map[string]interface{}) - - schedule := backup.SimpleSchedulePolicy{ //LongTermSchedulePolicy has no properties - SchedulePolicyType: backup.SchedulePolicyTypeSimpleSchedulePolicy, - ScheduleRunTimes: ×, - } - - if v, ok := block["frequency"].(string); ok { - schedule.ScheduleRunFrequency = backup.ScheduleRunType(v) - } - - if v, ok := block["weekdays"].(*schema.Set); ok { - days := make([]backup.DayOfWeek, 0) - for _, day := range v.List() { - days = append(days, backup.DayOfWeek(day.(string))) - } - schedule.ScheduleRunDays = &days - } - - return &schedule - } - - return nil -} - -func expandArmRecoveryServicesProtectionPolicyRetentionDaily(d *schema.ResourceData, times []date.Time) *backup.DailyRetentionSchedule { - if rb, ok := d.Get("retention_daily").([]interface{}); ok && len(rb) > 0 { - block := rb[0].(map[string]interface{}) - - return &backup.DailyRetentionSchedule{ - RetentionTimes: ×, - RetentionDuration: &backup.RetentionDuration{ - Count: utils.Int32(int32(block["count"].(int))), - DurationType: backup.RetentionDurationTypeDays, - }, - } - } - - return nil -} - -func expandArmRecoveryServicesProtectionPolicyRetentionWeekly(d *schema.ResourceData, times []date.Time) *backup.WeeklyRetentionSchedule { - if rb, ok := d.Get("retention_weekly").([]interface{}); ok && len(rb) > 0 { - block := rb[0].(map[string]interface{}) - - retention := backup.WeeklyRetentionSchedule{ - RetentionTimes: ×, - RetentionDuration: &backup.RetentionDuration{ - Count: utils.Int32(int32(block["count"].(int))), - DurationType: backup.RetentionDurationTypeWeeks, - }, - } - - if v, ok := block["weekdays"].(*schema.Set); ok { - days := make([]backup.DayOfWeek, 0) - for _, day := range v.List() { - days = append(days, backup.DayOfWeek(day.(string))) - } - retention.DaysOfTheWeek = &days - } - - return &retention - } - - return nil -} - -func expandArmRecoveryServicesProtectionPolicyRetentionMonthly(d *schema.ResourceData, times []date.Time) *backup.MonthlyRetentionSchedule { - if rb, ok := d.Get("retention_monthly").([]interface{}); ok && len(rb) > 0 { - block := rb[0].(map[string]interface{}) - - retention := backup.MonthlyRetentionSchedule{ - RetentionScheduleFormatType: backup.RetentionScheduleFormatWeekly, //this is always weekly ¯\_(ツ)_/¯ - RetentionScheduleDaily: nil, //and this is always nil.. - RetentionScheduleWeekly: expandArmRecoveryServicesProtectionPolicyRetentionWeeklyFormat(block), - RetentionTimes: ×, - RetentionDuration: &backup.RetentionDuration{ - Count: utils.Int32(int32(block["count"].(int))), - DurationType: backup.RetentionDurationTypeMonths, - }, - } - - return &retention - } - - return nil -} - -func expandArmRecoveryServicesProtectionPolicyRetentionYearly(d *schema.ResourceData, times []date.Time) *backup.YearlyRetentionSchedule { - if rb, ok := d.Get("retention_yearly").([]interface{}); ok && len(rb) > 0 { - block := rb[0].(map[string]interface{}) - - retention := backup.YearlyRetentionSchedule{ - RetentionScheduleFormatType: backup.RetentionScheduleFormatWeekly, //this is always weekly ¯\_(ツ)_/¯ - RetentionScheduleDaily: nil, //and this is always nil.. - RetentionScheduleWeekly: expandArmRecoveryServicesProtectionPolicyRetentionWeeklyFormat(block), - RetentionTimes: ×, - RetentionDuration: &backup.RetentionDuration{ - Count: utils.Int32(int32(block["count"].(int))), - DurationType: backup.RetentionDurationTypeYears, - }, - } - - if v, ok := block["months"].(*schema.Set); ok { - months := make([]backup.MonthOfYear, 0) - for _, month := range v.List() { - months = append(months, backup.MonthOfYear(month.(string))) - } - retention.MonthsOfYear = &months - } - - return &retention - } - - return nil -} - -func expandArmRecoveryServicesProtectionPolicyRetentionWeeklyFormat(block map[string]interface{}) *backup.WeeklyRetentionFormat { - weekly := backup.WeeklyRetentionFormat{} - - if v, ok := block["weekdays"].(*schema.Set); ok { - days := make([]backup.DayOfWeek, 0) - for _, day := range v.List() { - days = append(days, backup.DayOfWeek(day.(string))) - } - weekly.DaysOfTheWeek = &days - } - - if v, ok := block["weeks"].(*schema.Set); ok { - weeks := make([]backup.WeekOfMonth, 0) - for _, week := range v.List() { - weeks = append(weeks, backup.WeekOfMonth(week.(string))) - } - weekly.WeeksOfTheMonth = &weeks - } - - return &weekly -} - -func flattenArmRecoveryServicesProtectionPolicySchedule(schedule *backup.SimpleSchedulePolicy) []interface{} { - block := map[string]interface{}{} - - block["frequency"] = string(schedule.ScheduleRunFrequency) - - if times := schedule.ScheduleRunTimes; times != nil && len(*times) > 0 { - block["time"] = (*times)[0].Format("15:04") - } - - if days := schedule.ScheduleRunDays; days != nil { - weekdays := make([]interface{}, 0) - for _, d := range *days { - weekdays = append(weekdays, string(d)) - } - block["weekdays"] = schema.NewSet(schema.HashString, weekdays) - } - - return []interface{}{block} -} - -func flattenArmRecoveryServicesProtectionPolicyRetentionDaily(daily *backup.DailyRetentionSchedule) []interface{} { - block := map[string]interface{}{} - - if duration := daily.RetentionDuration; duration != nil { - if v := duration.Count; v != nil { - block["count"] = *v - } - } - - return []interface{}{block} -} - -func flattenArmRecoveryServicesProtectionPolicyRetentionWeekly(weekly *backup.WeeklyRetentionSchedule) []interface{} { - block := map[string]interface{}{} - - if duration := weekly.RetentionDuration; duration != nil { - if v := duration.Count; v != nil { - block["count"] = *v - } - } - - if days := weekly.DaysOfTheWeek; days != nil { - weekdays := make([]interface{}, 0) - for _, d := range *days { - weekdays = append(weekdays, string(d)) - } - block["weekdays"] = schema.NewSet(schema.HashString, weekdays) - } - - return []interface{}{block} -} - -func flattenArmRecoveryServicesProtectionPolicyRetentionMonthly(monthly *backup.MonthlyRetentionSchedule) []interface{} { - block := map[string]interface{}{} - - if duration := monthly.RetentionDuration; duration != nil { - if v := duration.Count; v != nil { - block["count"] = *v - } - } - - if weekly := monthly.RetentionScheduleWeekly; weekly != nil { - block["weekdays"], block["weeks"] = flattenArmRecoveryServicesProtectionPolicyRetentionWeeklyFormat(weekly) - } - - return []interface{}{block} -} - -func flattenArmRecoveryServicesProtectionPolicyRetentionYearly(yearly *backup.YearlyRetentionSchedule) []interface{} { - block := map[string]interface{}{} - - if duration := yearly.RetentionDuration; duration != nil { - if v := duration.Count; v != nil { - block["count"] = *v - } - } - - if weekly := yearly.RetentionScheduleWeekly; weekly != nil { - block["weekdays"], block["weeks"] = flattenArmRecoveryServicesProtectionPolicyRetentionWeeklyFormat(weekly) - } - - if months := yearly.MonthsOfYear; months != nil { - slice := make([]interface{}, 0) - for _, d := range *months { - slice = append(slice, string(d)) - } - block["months"] = schema.NewSet(schema.HashString, slice) - } - - return []interface{}{block} -} - -func flattenArmRecoveryServicesProtectionPolicyRetentionWeeklyFormat(retention *backup.WeeklyRetentionFormat) (weekdays, weeks *schema.Set) { - if days := retention.DaysOfTheWeek; days != nil { - slice := make([]interface{}, 0) - for _, d := range *days { - slice = append(slice, string(d)) - } - weekdays = schema.NewSet(schema.HashString, slice) - } - - if days := retention.WeeksOfTheMonth; days != nil { - slice := make([]interface{}, 0) - for _, d := range *days { - slice = append(slice, string(d)) - } - weeks = schema.NewSet(schema.HashString, slice) - } - - return weekdays, weeks -} - -func resourceArmRecoveryServicesProtectionPolicyWaitForUpdate(ctx context.Context, client *backup.ProtectionPoliciesClient, vaultName, resourceGroup, policyName string, d *schema.ResourceData) (backup.ProtectionPolicyResource, error) { - state := &resource.StateChangeConf{ - MinTimeout: 30 * time.Second, - Delay: 10 * time.Second, - Pending: []string{"NotFound"}, - Target: []string{"Found"}, - Refresh: resourceArmRecoveryServicesProtectionPolicyRefreshFunc(ctx, client, vaultName, resourceGroup, policyName), - } - - if d.IsNewResource() { - state.Timeout = d.Timeout(schema.TimeoutCreate) - } else { - state.Timeout = d.Timeout(schema.TimeoutUpdate) - } - - resp, err := state.WaitForState() - if err != nil { - return resp.(backup.ProtectionPolicyResource), fmt.Errorf("Error waiting for the Recovery Service Protection Policy %q to be true (Resource Group %q) to provision: %+v", policyName, resourceGroup, err) - } - - return resp.(backup.ProtectionPolicyResource), nil -} - -func resourceArmRecoveryServicesProtectionPolicyWaitForDeletion(ctx context.Context, client *backup.ProtectionPoliciesClient, vaultName, resourceGroup, policyName string, d *schema.ResourceData) (backup.ProtectionPolicyResource, error) { - state := &resource.StateChangeConf{ - MinTimeout: 30 * time.Second, - Delay: 10 * time.Second, - Pending: []string{"Found"}, - Target: []string{"NotFound"}, - Refresh: resourceArmRecoveryServicesProtectionPolicyRefreshFunc(ctx, client, vaultName, resourceGroup, policyName), - Timeout: d.Timeout(schema.TimeoutDelete), - } - - resp, err := state.WaitForState() - if err != nil { - return resp.(backup.ProtectionPolicyResource), fmt.Errorf("Error waiting for the Recovery Service Protection Policy %q to be false (Resource Group %q) to provision: %+v", policyName, resourceGroup, err) - } - - return resp.(backup.ProtectionPolicyResource), nil -} - -func resourceArmRecoveryServicesProtectionPolicyRefreshFunc(ctx context.Context, client *backup.ProtectionPoliciesClient, vaultName, resourceGroup, policyName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - resp, err := client.Get(ctx, vaultName, resourceGroup, policyName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return resp, "NotFound", nil - } - - return resp, "Error", fmt.Errorf("Error making Read request on Recovery Service Protection Policy %q (Resource Group %q): %+v", policyName, resourceGroup, err) - } - - return resp, "Found", nil - } -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replicated_vm.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replicated_vm.go deleted file mode 100644 index a93c4937d8d1..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replicated_vm.go +++ /dev/null @@ -1,353 +0,0 @@ -package recoveryservices - -import ( - "bytes" - "fmt" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute" - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2018-01-10/siterecovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesReplicatedVm() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_replicated_vm` resource is deprecated in favor of `azurerm_site_recovery_replicated_vm` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryReplicatedItemCreate, - Read: resourceArmRecoveryReplicatedItemRead, - Delete: resourceArmRecoveryReplicatedItemDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(80 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(80 * time.Minute), - Delete: schema.DefaultTimeout(80 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - "source_recovery_fabric_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "source_vm_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_recovery_fabric_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "recovery_replication_policy_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "source_recovery_protection_container_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "target_recovery_protection_container_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_resource_group_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_availability_set_id": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "managed_disk": { - Type: schema.TypeSet, - ConfigMode: schema.SchemaConfigModeAttr, - Optional: true, - ForceNew: true, - Set: resourceArmRecoveryReplicatedVmDiskHash, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "disk_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - DiffSuppressFunc: suppress.CaseDifference, - }, - "staging_storage_account_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_resource_group_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateResourceID, - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_disk_type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{ - string(compute.StandardLRS), - string(compute.PremiumLRS), - string(compute.StandardSSDLRS), - string(compute.UltraSSDLRS), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - "target_replica_disk_type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{ - string(compute.StandardLRS), - string(compute.PremiumLRS), - string(compute.StandardSSDLRS), - string(compute.UltraSSDLRS), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - }, - }, - }, - }, - }, - } -} - -func resourceArmRecoveryReplicatedItemCreate(d *schema.ResourceData, meta interface{}) error { - name := d.Get("name").(string) - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - fabricName := d.Get("source_recovery_fabric_name").(string) - sourceVmId := d.Get("source_vm_id").(string) - policyId := d.Get("recovery_replication_policy_id").(string) - sourceProtectionContainerName := d.Get("source_recovery_protection_container_name").(string) - targetProtectionContainerId := d.Get("target_recovery_protection_container_id").(string) - targetResourceGroupId := d.Get("target_resource_group_id").(string) - - var targetAvailabilitySetID *string - if id, isSet := d.GetOk("target_availability_set_id"); isSet { - tmp := id.(string) - targetAvailabilitySetID = &tmp - } else { - targetAvailabilitySetID = nil - } - - client := meta.(*clients.Client).RecoveryServices.ReplicationMigrationItemsClient(resGroup, vaultName) - ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) - defer cancel() - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, fabricName, sourceProtectionContainerName, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing recovery services replicated vm %s (vault %s): %+v", name, vaultName, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_replicated_vm", azure.HandleAzureSdkForGoBug2824(*existing.ID)) - } - } - - managedDisks := []siterecovery.A2AVMManagedDiskInputDetails{} - - for _, raw := range d.Get("managed_disk").(*schema.Set).List() { - 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) - - managedDisks = append(managedDisks, siterecovery.A2AVMManagedDiskInputDetails{ - DiskID: &diskId, - PrimaryStagingAzureStorageAccountID: &primaryStagingAzureStorageAccountID, - RecoveryResourceGroupID: &recoveryResourceGroupId, - RecoveryReplicaDiskAccountType: &targetReplicaDiskType, - RecoveryTargetDiskAccountType: &targetDiskType, - }) - } - - var parameters = siterecovery.EnableProtectionInput{ - Properties: &siterecovery.EnableProtectionInputProperties{ - PolicyID: &policyId, - ProviderSpecificDetails: siterecovery.A2AEnableProtectionInput{ - FabricObjectID: &sourceVmId, - RecoveryContainerID: &targetProtectionContainerId, - RecoveryResourceGroupID: &targetResourceGroupId, - RecoveryAvailabilitySetID: targetAvailabilitySetID, - VMManagedDisks: &managedDisks, - }, - }, - } - future, err := client.Create(ctx, fabricName, sourceProtectionContainerName, name, parameters) - if err != nil { - return fmt.Errorf("Error creating replicated vm %s (vault %s): %+v", name, vaultName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error creating replicated vm %s (vault %s): %+v", name, vaultName, err) - } - - resp, err := client.Get(ctx, fabricName, sourceProtectionContainerName, name) - if err != nil { - return fmt.Errorf("Error retrieving replicated vm %s (vault %s): %+v", name, vaultName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryReplicatedItemRead(d, meta) -} - -func resourceArmRecoveryReplicatedItemRead(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - protectionContainerName := id.Path["replicationProtectionContainers"] - name := id.Path["replicationProtectedItems"] - - client := meta.(*clients.Client).RecoveryServices.ReplicationMigrationItemsClient(resGroup, vaultName) - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resp, err := client.Get(ctx, fabricName, protectionContainerName, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making Read request on recovery services replicated vm %s (vault %s): %+v", name, vaultName, err) - } - - d.Set("name", name) - d.Set("resource_group_name", resGroup) - d.Set("recovery_vault_name", vaultName) - d.Set("source_recovery_fabric_name", fabricName) - d.Set("target_recovery_fabric_id", resp.Properties.RecoveryFabricID) - d.Set("recovery_replication_policy_id", resp.Properties.PolicyID) - d.Set("source_recovery_protection_container_name", protectionContainerName) - d.Set("target_recovery_protection_container_id", resp.Properties.RecoveryContainerID) - - if a2aDetails, isA2a := resp.Properties.ProviderSpecificDetails.AsA2AReplicationDetails(); isA2a { - d.Set("source_vm_id", a2aDetails.FabricObjectID) - d.Set("target_resource_group_id", a2aDetails.RecoveryAzureResourceGroupID) - d.Set("target_availability_set_id", a2aDetails.RecoveryAvailabilitySet) - if a2aDetails.ProtectedManagedDisks != nil { - disksOutput := make([]interface{}, 0) - for _, disk := range *a2aDetails.ProtectedManagedDisks { - diskOutput := make(map[string]interface{}) - diskOutput["disk_id"] = *disk.DiskID - diskOutput["staging_storage_account_id"] = *disk.PrimaryStagingAzureStorageAccountID - diskOutput["target_resource_group_id"] = *disk.RecoveryResourceGroupID - diskOutput["target_replica_disk_type"] = *disk.RecoveryReplicaDiskAccountType - diskOutput["target_disk_type"] = *disk.RecoveryTargetDiskAccountType - - disksOutput = append(disksOutput, diskOutput) - } - d.Set("managed_disk", schema.NewSet(resourceArmRecoveryReplicatedVmDiskHash, disksOutput)) - } - } - - return nil -} - -func resourceArmRecoveryReplicatedItemDelete(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - fabricName := id.Path["replicationFabrics"] - protectionContainerName := id.Path["replicationProtectionContainers"] - name := id.Path["replicationProtectedItems"] - - disableProtectionInput := siterecovery.DisableProtectionInput{ - Properties: &siterecovery.DisableProtectionInputProperties{ - DisableProtectionReason: siterecovery.NotSpecified, - ReplicationProviderInput: siterecovery.DisableProtectionProviderSpecificInput{}, - }, - } - - client := meta.(*clients.Client).RecoveryServices.ReplicationMigrationItemsClient(resGroup, vaultName) - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - future, err := client.Delete(ctx, fabricName, protectionContainerName, name, disableProtectionInput) - if err != nil { - return fmt.Errorf("Error deleting recovery services replicated vm %s (vault %s): %+v", name, vaultName, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of recovery services replicated vm %s (vault %s): %+v", name, vaultName, err) - } - return nil -} - -func resourceArmRecoveryReplicatedVmDiskHash(v interface{}) int { - var buf bytes.Buffer - - if m, ok := v.(map[string]interface{}); ok { - if v, ok := m["disk_id"]; ok { - buf.WriteString(strings.ToLower(v.(string))) - } - } - - return hashcode.String(buf.String()) -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replication_policy.go b/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replication_policy.go deleted file mode 100644 index 2288499b6ac5..000000000000 --- a/azurerm/internal/services/recoveryservices/resource_arm_recovery_services_replication_policy.go +++ /dev/null @@ -1,215 +0,0 @@ -package recoveryservices - -import ( - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2018-01-10/siterecovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmRecoveryServicesReplicationPolicy() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: "`azurerm_recovery_services_replication_policy` resource is deprecated in favor of `azurerm_site_recovery_replication_policy` and will be removed in v2.0 of the AzureRM Provider", - Create: resourceArmRecoveryServicesReplicationPolicyCreate, - Read: resourceArmRecoveryServicesReplicationPolicyRead, - Update: resourceArmRecoveryServicesReplicationPolicyUpdate, - Delete: resourceArmRecoveryServicesReplicationPolicyDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(30 * time.Minute), - Read: schema.DefaultTimeout(5 * time.Minute), - Update: schema.DefaultTimeout(30 * time.Minute), - Delete: schema.DefaultTimeout(30 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "resource_group_name": azure.SchemaResourceGroupName(), - - "recovery_vault_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateRecoveryServicesVaultName, - }, - "recovery_point_retention_in_minutes": { - Type: schema.TypeInt, - Required: true, - ForceNew: false, - ValidateFunc: validation.IntBetween(1, 365*24*60), - }, - "application_consistent_snapshot_frequency_in_minutes": { - Type: schema.TypeInt, - Required: true, - ForceNew: false, - ValidateFunc: validation.IntBetween(1, 365*24*60), - }, - }, - } -} - -func resourceArmRecoveryServicesReplicationPolicyCreate(d *schema.ResourceData, meta interface{}) error { - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - name := d.Get("name").(string) - - client := meta.(*clients.Client).RecoveryServices.ReplicationPoliciesClient(resGroup, vaultName) - ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) - defer cancel() - - if features.ShouldResourcesBeImported() && d.IsNewResource() { - existing, err := client.Get(ctx, name) - if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing recovery services replication policy %s: %+v", name, err) - } - } - - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_services_replication_policy", azure.HandleAzureSdkForGoBug2824(*existing.ID)) - } - } - - recoveryPoint := int32(d.Get("recovery_point_retention_in_minutes").(int)) - appConsitency := int32(d.Get("application_consistent_snapshot_frequency_in_minutes").(int)) - var parameters = siterecovery.CreatePolicyInput{ - Properties: &siterecovery.CreatePolicyInputProperties{ - ProviderSpecificInput: &siterecovery.A2APolicyCreationInput{ - RecoveryPointHistory: &recoveryPoint, - AppConsistentFrequencyInMinutes: &appConsitency, - MultiVMSyncStatus: siterecovery.Enable, - InstanceType: siterecovery.InstanceTypeBasicPolicyProviderSpecificInputInstanceTypeA2A, - }, - }, - } - future, err := client.Create(ctx, name, parameters) - if err != nil { - return fmt.Errorf("Error creating recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error creating recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - - resp, err := client.Get(ctx, name) - if err != nil { - return fmt.Errorf("Error retrieving site recovery replication policy %s (vault %s): %+v", name, vaultName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryServicesReplicationPolicyRead(d, meta) -} - -func resourceArmRecoveryServicesReplicationPolicyUpdate(d *schema.ResourceData, meta interface{}) error { - resGroup := d.Get("resource_group_name").(string) - vaultName := d.Get("recovery_vault_name").(string) - name := d.Get("name").(string) - - client := meta.(*clients.Client).RecoveryServices.ReplicationPoliciesClient(resGroup, vaultName) - ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) - defer cancel() - - recoveryPoint := int32(d.Get("recovery_point_retention_in_minutes").(int)) - appConsitency := int32(d.Get("application_consistent_snapshot_frequency_in_minutes").(int)) - var parameters = siterecovery.UpdatePolicyInput{ - Properties: &siterecovery.UpdatePolicyInputProperties{ - ReplicationProviderSettings: &siterecovery.A2APolicyCreationInput{ - RecoveryPointHistory: &recoveryPoint, - AppConsistentFrequencyInMinutes: &appConsitency, - MultiVMSyncStatus: siterecovery.Enable, - InstanceType: siterecovery.InstanceTypeBasicPolicyProviderSpecificInputInstanceTypeA2A, - }, - }, - } - future, err := client.Update(ctx, name, parameters) - if err != nil { - return fmt.Errorf("Error updating recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error updating recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - - resp, err := client.Get(ctx, name) - if err != nil { - return fmt.Errorf("Error retrieving site recovery replication policy %s (vault %s): %+v", name, vaultName, err) - } - - d.SetId(azure.HandleAzureSdkForGoBug2824(*resp.ID)) - - return resourceArmRecoveryServicesReplicationPolicyRead(d, meta) -} - -func resourceArmRecoveryServicesReplicationPolicyRead(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - name := id.Path["replicationPolicies"] - - client := meta.(*clients.Client).RecoveryServices.ReplicationPoliciesClient(resGroup, vaultName) - ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - defer cancel() - - resp, err := client.Get(ctx, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making Read request on recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - - d.Set("name", resp.Name) - d.Set("resource_group_name", resGroup) - d.Set("recovery_vault_name", vaultName) - if a2APolicyDetails, isA2A := resp.Properties.ProviderSpecificDetails.AsA2APolicyDetails(); isA2A { - d.Set("recovery_point_retention_in_minutes", a2APolicyDetails.RecoveryPointHistory) - d.Set("application_consistent_snapshot_frequency_in_minutes", a2APolicyDetails.AppConsistentFrequencyInMinutes) - } - return nil -} - -func resourceArmRecoveryServicesReplicationPolicyDelete(d *schema.ResourceData, meta interface{}) error { - id, err := azure.ParseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resGroup := id.ResourceGroup - vaultName := id.Path["vaults"] - name := id.Path["replicationPolicies"] - - client := meta.(*clients.Client).RecoveryServices.ReplicationPoliciesClient(resGroup, vaultName) - ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) - defer cancel() - - future, err := client.Delete(ctx, name) - if err != nil { - return fmt.Errorf("Error deleting recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of recovery services replication policy %s (vault %s): %+v", name, vaultName, err) - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/resource_arm_site_recovery_protection_container.go b/azurerm/internal/services/recoveryservices/resource_arm_site_recovery_protection_container.go index ec0c32c3bb11..d0497ccd1f71 100644 --- a/azurerm/internal/services/recoveryservices/resource_arm_site_recovery_protection_container.go +++ b/azurerm/internal/services/recoveryservices/resource_arm_site_recovery_protection_container.go @@ -76,7 +76,7 @@ func resourceArmSiteRecoveryProtectionContainerCreate(d *schema.ResourceData, me } if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_recovery_services_protection_container", azure.HandleAzureSdkForGoBug2824(*existing.ID)) + return tf.ImportAsExistsError("azurerm_site_recovery_protection_container", azure.HandleAzureSdkForGoBug2824(*existing.ID)) } } diff --git a/azurerm/internal/services/recoveryservices/tests/data_source_recovery_services_protection_policy_vm_test.go b/azurerm/internal/services/recoveryservices/tests/data_source_backup_policy_vm_test.go similarity index 53% rename from azurerm/internal/services/recoveryservices/tests/data_source_recovery_services_protection_policy_vm_test.go rename to azurerm/internal/services/recoveryservices/tests/data_source_backup_policy_vm_test.go index 03af8b3759ef..80c6f1027268 100644 --- a/azurerm/internal/services/recoveryservices/tests/data_source_recovery_services_protection_policy_vm_test.go +++ b/azurerm/internal/services/recoveryservices/tests/data_source_backup_policy_vm_test.go @@ -8,17 +8,17 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" ) -func TestAccDataSourceAzureRMRecoveryServicesProtectionPolicyVm_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "data.azurerm_recovery_services_protection_policy_vm", "test") +func TestAccDataSourceAzureRMBackupProtectionPolicyVm_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_backup_policy_vm", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, Steps: []resource.TestStep{ { - Config: testAccDataSourceRecoveryServicesProtectionPolicyVm_basic(data), + Config: testAccDataSourceBackupPolicyVm_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(data.ResourceName), + testCheckAzureRMBackupProtectionPolicyVmExists(data.ResourceName), resource.TestCheckResourceAttrSet(data.ResourceName, "name"), resource.TestCheckResourceAttrSet(data.ResourceName, "recovery_vault_name"), resource.TestCheckResourceAttrSet(data.ResourceName, "resource_group_name"), @@ -29,14 +29,14 @@ func TestAccDataSourceAzureRMRecoveryServicesProtectionPolicyVm_basic(t *testing }) } -func testAccDataSourceRecoveryServicesProtectionPolicyVm_basic(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data) +func testAccDataSourceBackupPolicyVm_basic(data acceptance.TestData) string { + template := testAccAzureRMBackupProtectionPolicyVM_basicDaily(data) return fmt.Sprintf(` %s -data "azurerm_recovery_services_protection_policy_vm" "test" { - name = "${azurerm_recovery_services_protection_policy_vm.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" +data "azurerm_backup_policy_vm" "test" { + name = "${azurerm_backup_policy_vm.test.name}" + recovery_vault_name = "${azurerm_backup_vault.test.name}" resource_group_name = "${azurerm_resource_group.test.name}" } `, template) diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_fabric_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_fabric_test.go deleted file mode 100644 index c832d65df33a..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_fabric_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" -) - -func TestAccAzureRMRecoveryFabric_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_fabric", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryFabricDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryFabric_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryFabricExists(data.ResourceName), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMRecoveryFabric_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-vault-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_fabric" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric-%d" - location = "${azurerm_resource_group.test.location}" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) -} - -func testCheckAzureRMRecoveryFabricExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - state, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroupName := state.Primary.Attributes["resource_group_name"] - vaultName := state.Primary.Attributes["recovery_vault_name"] - fabricName := state.Primary.Attributes["name"] - - // Ensure fabric exists in API - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.FabricClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName) - if err != nil { - return fmt.Errorf("Bad: Get on fabricClient: %+v", err) - } - - if resp.Response.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: fabric: %q does not exist", fabricName) - } - - return nil - } -} - -func testCheckAzureRMRecoveryFabricDestroy(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_services_fabric" { - continue - } - - resourceGroupName := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - resourceGroup := rs.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.FabricClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, resourceGroup) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Recovery Services Fabric still exists:\n%#v", resp.Properties) - } - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_network_mapping_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_network_mapping_test.go deleted file mode 100644 index fb9148d2e009..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_network_mapping_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" -) - -func TestAccAzureRMRecoveryNetworkMapping_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_network_mapping", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryNetworkMappingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryNetworkMapping_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryNetworkMappingExists(data.ResourceName), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMRecoveryNetworkMapping_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d-1" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-vault-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_fabric" "test1" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric1-%d" - location = "${azurerm_resource_group.test.location}" -} - -resource "azurerm_recovery_services_fabric" "test2" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric2-%d" - location = "%s" - depends_on = ["azurerm_recovery_services_fabric.test1"] -} - -resource "azurerm_virtual_network" "test1" { - name = "network1-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - address_space = ["192.168.1.0/24"] - location = "${azurerm_recovery_services_fabric.test1.location}" -} - -resource "azurerm_virtual_network" "test2" { - name = "network2-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - address_space = ["192.168.2.0/24"] - location = "${azurerm_recovery_services_fabric.test2.location}" -} - -resource "azurerm_recovery_network_mapping" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "mapping-%d" - source_recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - target_recovery_fabric_name = "${azurerm_recovery_services_fabric.test2.name}" - source_network_id = "${azurerm_virtual_network.test1.id}" - target_network_id = "${azurerm_virtual_network.test2.id}" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.Locations.Secondary, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testCheckAzureRMRecoveryNetworkMappingExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - state, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroupName := state.Primary.Attributes["resource_group_name"] - vaultName := state.Primary.Attributes["recovery_vault_name"] - fabricName := state.Primary.Attributes["source_recovery_fabric_name"] - networkId := state.Primary.Attributes["source_network_id"] - mappingName := state.Primary.Attributes["name"] - - id, err := azure.ParseAzureResourceID(networkId) - if err != nil { - return err - } - networkName := id.Path["virtualNetworks"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.NetworkMappingClient(resourceGroupName, vaultName) - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // TODO Fix Bad: networkMapping error - resp, err := client.Get(ctx, fabricName, networkName, mappingName) - if err != nil { - if resp.Response.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: networkMapping: %q (network %q) does not exist", mappingName, networkName) - } - - return fmt.Errorf("Bad: Get on networkMappingClient: %+v", err) - } - - return nil - } -} - -func testCheckAzureRMRecoveryNetworkMappingDestroy(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_network_mapping" { - continue - } - - resourceGroupName := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - fabricName := rs.Primary.Attributes["source_recovery_fabric_name"] - networkId := rs.Primary.Attributes["source_network_id"] - mappingName := rs.Primary.Attributes["name"] - - id, err := azure.ParseAzureResourceID(networkId) - if err != nil { - return err - } - networkName := id.Path["virtualNetworks"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.NetworkMappingClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, networkName, mappingName) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Network Mapping still exists:\n%#v", resp.Properties) - } - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protected_vm_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protected_vm_test.go deleted file mode 100644 index 6fcb6c1e6d36..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protected_vm_test.go +++ /dev/null @@ -1,642 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func TestAccAzureRMRecoveryServicesProtectedVm_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protected_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectedVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectedVm_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectedVmExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "resource_group_name"), - ), - }, - data.ImportStep(), - { //vault cannot be deleted unless we unregister all backups - Config: testAccAzureRMRecoveryServicesProtectedVm_base(data), - Check: resource.ComposeTestCheckFunc(), - }, - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectedVm_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protected_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectedVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectedVm_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectedVmExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "resource_group_name"), - ), - }, - data.RequiresImportErrorStep(testAccAzureRMRecoveryServicesProtectedVm_requiresImport), - { //vault cannot be deleted unless we unregister all backups - Config: testAccAzureRMRecoveryServicesProtectedVm_base(data), - Check: resource.ComposeTestCheckFunc(), - }, - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectedVm_separateResourceGroups(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protected_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectedVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectedVm_separateResourceGroups(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectedVmExists(data.ResourceName), - resource.TestCheckResourceAttrSet(data.ResourceName, "resource_group_name"), - ), - }, - data.ImportStep(), - { //vault cannot be deleted unless we unregister all backups - Config: testAccAzureRMRecoveryServicesProtectedVm_additionalVault(data), - Check: resource.ComposeTestCheckFunc(), - }, - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectedVm_updateBackupPolicyId(t *testing.T) { - virtualMachine := "azurerm_virtual_machine.test" - fBackupPolicyResourceName := "azurerm_recovery_services_protection_policy_vm.test" - sBackupPolicyResourceName := "azurerm_recovery_services_protection_policy_vm.test_change_backup" - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protected_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectedVmDestroy, - Steps: []resource.TestStep{ - { // Create resources and link first backup policy id - ResourceName: fBackupPolicyResourceName, - Config: testAccAzureRMRecoveryServicesProtectedVm_linkFirstBackupPolicy(data), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(data.ResourceName, "backup_policy_id", fBackupPolicyResourceName, "id"), - ), - }, - { // Modify backup policy id to the second one - // Set Destroy false to prevent error from cleaning up dangling resource - ResourceName: sBackupPolicyResourceName, - Config: testAccAzureRMRecoveryServicesProtectedVm_linkSecondBackupPolicy(data), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(data.ResourceName, "backup_policy_id", sBackupPolicyResourceName, "id"), - ), - }, - { // Remove backup policy link - // Backup policy link will need to be removed first so the VM's backup policy subsequently reverts to Default - // Azure API is quite sensitive, adding the step to control resource cleanup order - ResourceName: fBackupPolicyResourceName, - Config: testAccAzureRMRecoveryServicesProtectedVm_withVM(data), - Check: resource.ComposeTestCheckFunc(), - }, - { // Then VM can be removed - ResourceName: virtualMachine, - Config: testAccAzureRMRecoveryServicesProtectedVm_withSecondPolicy(data), - Check: resource.ComposeTestCheckFunc(), - }, - { // Remove backup policies and vault - ResourceName: data.ResourceName, - Config: testAccAzureRMRecoveryServicesProtectedVm_basePolicyTest(data), - Check: resource.ComposeTestCheckFunc(), - }, - }, - }) -} - -func testCheckAzureRMRecoveryServicesProtectedVmDestroy(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ProtectedItemsClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_services_protected_vm" { - continue - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - vmId := rs.Primary.Attributes["source_vm_id"] - - parsedVmId, err := azure.ParseAzureResourceID(vmId) - if err != nil { - return fmt.Errorf("[ERROR] Unable to parse source_vm_id '%s': %+v", vmId, err) - } - vmName, hasName := parsedVmId.Path["virtualMachines"] - if !hasName { - return fmt.Errorf("[ERROR] parsed source_vm_id '%s' doesn't contain 'virtualMachines'", vmId) - } - - protectedItemName := fmt.Sprintf("VM;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroup, vmName) - containerName := fmt.Sprintf("iaasvmcontainer;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroup, vmName) - - resp, err := client.Get(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName, "") - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return nil - } - - return err - } - - return fmt.Errorf("Recovery Services Protected VM still exists:\n%#v", resp) - } - - return nil -} - -func testCheckAzureRMRecoveryServicesProtectedVmExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ProtectedItemsClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %q", resourceName) - } - - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for Recovery Services Protected VM: %q", resourceName) - } - - vaultName := rs.Primary.Attributes["recovery_vault_name"] - vmId := rs.Primary.Attributes["source_vm_id"] - - //get VM name from id - parsedVmId, err := azure.ParseAzureResourceID(vmId) - if err != nil { - return fmt.Errorf("[ERROR] Unable to parse source_vm_id '%s': %+v", vmId, err) - } - vmName, hasName := parsedVmId.Path["virtualMachines"] - if !hasName { - return fmt.Errorf("[ERROR] parsed source_vm_id '%s' doesn't contain 'virtualMachines'", vmId) - } - - protectedItemName := fmt.Sprintf("VM;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroup, vmName) - containerName := fmt.Sprintf("iaasvmcontainer;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroup, vmName) - - resp, err := client.Get(ctx, vaultName, resourceGroup, "Azure", containerName, protectedItemName, "") - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Recovery Services Protected VM %q (resource group: %q) was not found: %+v", protectedItemName, resourceGroup, err) - } - - return fmt.Errorf("Bad: Get on recoveryServicesVaultsClient: %+v", err) - } - - return nil - } -} - -func testAccAzureRMRecoveryServicesProtectedVm_base(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d" - location = "%s" -} - -resource "azurerm_virtual_network" "test" { - name = "vnet" - location = "${azurerm_resource_group.test.location}" - address_space = ["10.0.0.0/16"] - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctest_subnet" - virtual_network_name = "${azurerm_virtual_network.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - address_prefix = "10.0.10.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctest_nic" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "acctestipconfig" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - public_ip_address_id = "${azurerm_public_ip.test.id}" - } -} - -resource "azurerm_public_ip" "test" { - name = "acctest-ip" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - allocation_method = "Dynamic" - domain_name_label = "acctestip%d" -} - -resource "azurerm_storage_account" "test" { - name = "acctest%s" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - account_tier = "Standard" - account_replication_type = "LRS" -} - -resource "azurerm_managed_disk" "test" { - name = "acctest-datadisk" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_type = "Standard_LRS" - create_option = "Empty" - disk_size_gb = "1023" -} - -resource "azurerm_virtual_machine" "test" { - name = "acctestvm" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - vm_size = "Standard_A0" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "acctest-osdisk" - managed_disk_type = "Standard_LRS" - caching = "ReadWrite" - create_option = "FromImage" - } - - storage_data_disk { - name = "acctest-datadisk" - managed_disk_id = "${azurerm_managed_disk.test.id}" - managed_disk_type = "Standard_LRS" - disk_size_gb = "${azurerm_managed_disk.test.disk_size_gb}" - create_option = "Attach" - lun = 0 - } - - os_profile { - computer_name = "acctest" - admin_username = "vmadmin" - admin_password = "Password123!@#" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - boot_diagnostics { - enabled = true - storage_uri = "${azurerm_storage_account.test.primary_blob_endpoint}" - } -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 10 - } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomString, data.RandomInteger, data.RandomInteger) -} - -func testAccAzureRMRecoveryServicesProtectedVm_basic(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protected_vm" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - source_vm_id = "${azurerm_virtual_machine.test.id}" - backup_policy_id = "${azurerm_recovery_services_protection_policy_vm.test.id}" -} -`, template) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_basePolicyTest(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d-1" - location = "%s" -} - -resource "azurerm_virtual_network" "test" { - name = "vnet" - location = "${azurerm_resource_group.test.location}" - address_space = ["10.0.0.0/16"] - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctest_subnet" - virtual_network_name = "${azurerm_virtual_network.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - address_prefix = "10.0.10.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctest_nic" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "acctestipconfig" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "Dynamic" - public_ip_address_id = "${azurerm_public_ip.test.id}" - } -} - -resource "azurerm_public_ip" "test" { - name = "acctest-ip" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - allocation_method = "Dynamic" - domain_name_label = "acctestip%d" -} - -resource "azurerm_storage_account" "test" { - name = "acctest%s" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - account_tier = "Standard" - account_replication_type = "LRS" -} - -resource "azurerm_managed_disk" "test" { - name = "acctest-datadisk" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_type = "Standard_LRS" - create_option = "Empty" - disk_size_gb = "1023" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomString) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_withVault(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_basePolicyTest(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} -`, template, data.RandomInteger) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_withFirstPolicy(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_withVault(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 10 - } -} -`, template, data.RandomInteger) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_withSecondPolicy(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_withFirstPolicy(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test_change_backup" { - name = "acctest2-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 15 - } -} -`, template, data.RandomInteger) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_withVM(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_withSecondPolicy(data) - return fmt.Sprintf(` -%s - -resource "azurerm_virtual_machine" "test" { - name = "acctestvm-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - vm_size = "Standard_A0" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - delete_os_disk_on_termination = true - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "acctest-osdisk" - managed_disk_type = "Standard_LRS" - caching = "ReadWrite" - create_option = "FromImage" - } - - storage_data_disk { - name = "acctest-datadisk" - managed_disk_id = "${azurerm_managed_disk.test.id}" - managed_disk_type = "Standard_LRS" - disk_size_gb = "${azurerm_managed_disk.test.disk_size_gb}" - create_option = "Attach" - lun = 0 - } - - os_profile { - computer_name = "acctest" - admin_username = "vmadmin" - admin_password = "Password123!@#" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - boot_diagnostics { - enabled = true - storage_uri = "${azurerm_storage_account.test.primary_blob_endpoint}" - } -} -`, template, data.RandomInteger) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_linkFirstBackupPolicy(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_withVM(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protected_vm" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - source_vm_id = "${azurerm_virtual_machine.test.id}" - backup_policy_id = "${azurerm_recovery_services_protection_policy_vm.test.id}" -} -`, template) -} - -// For update backup policy id test -func testAccAzureRMRecoveryServicesProtectedVm_linkSecondBackupPolicy(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_withVM(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protected_vm" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - source_vm_id = "${azurerm_virtual_machine.test.id}" - backup_policy_id = "${azurerm_recovery_services_protection_policy_vm.test_change_backup.id}" -} -`, template) -} - -func testAccAzureRMRecoveryServicesProtectedVm_requiresImport(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_basic(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protected_vm" "import" { - resource_group_name = "${azurerm_recovery_services_protected_vm.test.resource_group_name}" - recovery_vault_name = "${azurerm_recovery_services_protected_vm.test.recovery_vault_name}" - source_vm_id = "${azurerm_recovery_services_protected_vm.test.source_vm_id}" - backup_policy_id = "${azurerm_recovery_services_protected_vm.test.backup_policy_id}" -} -`, template) -} - -func testAccAzureRMRecoveryServicesProtectedVm_additionalVault(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_resource_group" "test2" { - name = "acctestRG-recovery-%d-2" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test2" { - name = "acctest2-%d" - location = "${azurerm_resource_group.test2.location}" - resource_group_name = "${azurerm_resource_group.test2.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_protection_policy_vm" "test2" { - name = "acctest2-%d" - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test2.name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 10 - } -} -`, template, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) -} - -func testAccAzureRMRecoveryServicesProtectedVm_separateResourceGroups(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectedVm_additionalVault(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protected_vm" "test" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test2.name}" - backup_policy_id = "${azurerm_recovery_services_protection_policy_vm.test2.id}" - source_vm_id = "${azurerm_virtual_machine.test.id}" -} -`, template) -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_mapping_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_mapping_test.go deleted file mode 100644 index 9bd3f3eabebe..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_mapping_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" -) - -func TestAccAzureRMRecoveryProtectionContainerMapping_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_container_mapping", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryProtectionContainerMappingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryProtectionContainerMapping_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryProtectionContainerMappingExists(data.ResourceName), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMRecoveryProtectionContainerMapping_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test1" { - name = "acctestRG-recovery-%d-1" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-vault-%d" - location = "${azurerm_resource_group.test1.location}" - resource_group_name = "${azurerm_resource_group.test1.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_fabric" "test1" { - resource_group_name = "${azurerm_resource_group.test1.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric1-%d" - location = "${azurerm_resource_group.test1.location}" -} - -resource "azurerm_recovery_services_fabric" "test2" { - resource_group_name = "${azurerm_resource_group.test1.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric2-%d" - location = "%s" - depends_on = ["azurerm_recovery_services_fabric.test1"] -} - -resource "azurerm_recovery_services_protection_container" "test1" { - resource_group_name = "${azurerm_resource_group.test1.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - name = "acctest-protection-cont1-%d" -} - -resource "azurerm_recovery_services_protection_container" "test2" { - resource_group_name = "${azurerm_resource_group.test1.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test2.name}" - name = "acctest-protection-cont2-%d" -} - -resource "azurerm_recovery_services_replication_policy" "test" { - resource_group_name = "${azurerm_resource_group.test1.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-policy-%d" - recovery_point_retention_in_minutes = "${24 * 60}" - application_consistent_snapshot_frequency_in_minutes = "${4 * 60}" -} - -resource "azurerm_recovery_services_protection_container_mapping" "test" { - resource_group_name = "${azurerm_resource_group.test1.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - recovery_source_protection_container_name = "${azurerm_recovery_services_protection_container.test1.name}" - recovery_target_protection_container_id = "${azurerm_recovery_services_protection_container.test2.id}" - recovery_replication_policy_id = "${azurerm_recovery_services_replication_policy.test.id}" - name = "mapping-%d" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.Locations.Secondary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testCheckAzureRMRecoveryProtectionContainerMappingExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - state, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroupName := state.Primary.Attributes["resource_group_name"] - vaultName := state.Primary.Attributes["recovery_vault_name"] - fabricName := state.Primary.Attributes["recovery_fabric_name"] - protectionContainerName := state.Primary.Attributes["recovery_source_protection_container_name"] - mappingName := state.Primary.Attributes["name"] - - // Ensure mapping exists in API - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ContainerMappingClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, protectionContainerName, mappingName) - if err != nil { - return fmt.Errorf("Bad: Get on fabricClient: %+v", err) - } - - if resp.Response.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: fabric: %q does not exist", fabricName) - } - - return nil - } -} - -func testCheckAzureRMRecoveryProtectionContainerMappingDestroy(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_services_protection_container_mapping" { - continue - } - - resourceGroupName := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - fabricName := rs.Primary.Attributes["recovery_fabric_name"] - protectionContainerName := rs.Primary.Attributes["recovery_source_protection_container_name"] - mappingName := rs.Primary.Attributes["name"] - - // Ensure mapping exists in API - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ContainerMappingClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, protectionContainerName, mappingName) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Container Mapping still exists:\n%#v", resp.Properties) - } - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_test.go deleted file mode 100644 index 28144fd3ae13..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_container_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" -) - -func TestAccAzureRMRecoveryProtectionContainer_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_container", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryProtectionContainerDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryProtectionContainer_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryProtectionContainerExists(data.ResourceName), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMRecoveryProtectionContainer_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-vault-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_fabric" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric-%d" - location = "${azurerm_resource_group.test.location}" -} - -resource "azurerm_recovery_services_protection_container" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test.name}" - name = "acctest-protection-cont-%d" -} - -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testCheckAzureRMRecoveryProtectionContainerExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - state, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroupName := state.Primary.Attributes["resource_group_name"] - vaultName := state.Primary.Attributes["recovery_vault_name"] - fabricName := state.Primary.Attributes["recovery_fabric_name"] - protectionContainerName := state.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ProtectionContainerClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, protectionContainerName) - if err != nil { - return fmt.Errorf("Bad: Get on RecoveryServices.ProtectionContainerClient: %+v", err) - } - - if resp.Response.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Protection Container: %q does not exist", fabricName) - } - - return nil - } -} - -func testCheckAzureRMRecoveryProtectionContainerDestroy(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_services_protection_container" { - continue - } - - resourceGroupName := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - fabricName := rs.Primary.Attributes["recovery_fabric_name"] - protectionContainerName := rs.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ProtectionContainerClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, protectionContainerName) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Protection Container Client still exists:\n%#v", resp.Properties) - } - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_policy_vm_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_policy_vm_test.go deleted file mode 100644 index 06811f24f723..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_protection_policy_vm_test.go +++ /dev/null @@ -1,555 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_requiresImport(t *testing.T) { - if !features.ShouldResourcesBeImported() { - t.Skip("Skipping since resources aren't required to be imported") - return - } - - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data.ResourceName, data.RandomInteger), - }, - data.RequiresImportErrorStep(testAccAzureRMRecoveryServicesProtectionPolicyVm_requiresImport), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_updateDaily(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data.ResourceName, data.RandomInteger), - }, - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_updateWeekly(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data.ResourceName, data.RandomInteger), - }, - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_updateDailyToWeekly(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data.ResourceName, data.RandomInteger), - }, - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_updateWeeklyToDaily(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data.ResourceName, data.RandomInteger), - }, - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func TestAccAzureRMRecoveryServicesProtectionPolicyVm_updateWeeklyToPartial(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_protection_policy_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data.ResourceName, data.RandomInteger), - }, - { - Config: testAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeeklyPartial(data), - Check: checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeeklyPartial(data.ResourceName, data.RandomInteger), - }, - data.ImportStep(), - }, - }) -} - -func testCheckAzureRMRecoveryServicesProtectionPolicyVmDestroy(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ProtectionPoliciesClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_services_protection_policy_vm" { - continue - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - policyName := rs.Primary.Attributes["name"] - - resp, err := client.Get(ctx, vaultName, resourceGroup, policyName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return nil - } - - return err - } - - return fmt.Errorf("Recovery Services Vault Policy still exists:\n%#v", resp) - } - - return nil -} - -func testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ProtectionPoliciesClient - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %q", resourceName) - } - - vaultName := rs.Primary.Attributes["recovery_vault_name"] - policyName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for Recovery Services Vault %q Policy: %q", vaultName, policyName) - } - - resp, err := client.Get(ctx, vaultName, resourceGroup, policyName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Recovery Services Vault Policy %q (resource group: %q) was not found: %+v", policyName, resourceGroup, err) - } - - return fmt.Errorf("Bad: Get on recoveryServicesVaultsClient: %+v", err) - } - - return nil - } -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_base(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%[1]d" - location = "%[2]s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-%[1]d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} -`, data.RandomInteger, data.Locations.Primary) -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 10 - } -} -`, template, data.RandomInteger) -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_requiresImport(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "import" { - name = "${azurerm_recovery_services_protection_policy_vm.test.name}" - resource_group_name = "${azurerm_recovery_services_protection_policy_vm.test.resource_group_name}" - recovery_vault_name = "${azurerm_recovery_services_protection_policy_vm.test.recovery_vault_name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 10 - } -} -`, template) -} - -func checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicDaily(resourceName string, ri int) resource.TestCheckFunc { - return resource.ComposeAggregateTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "resource_group_name", fmt.Sprintf("acctestRG-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "recovery_vault_name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backup.0.frequency", "Daily"), - resource.TestCheckResourceAttr(resourceName, "backup.0.time", "23:00"), - resource.TestCheckResourceAttr(resourceName, "retention_daily.0.count", "10"), - ) -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Weekly" - time = "23:00" - weekdays = ["Sunday", "Wednesday"] - } - - retention_weekly { - count = 42 - weekdays = ["Sunday", "Wednesday"] - } -} -`, template, data.RandomInteger) -} - -func checkAccAzureRMRecoveryServicesProtectionPolicyVm_basicWeekly(resourceName string, ri int) resource.TestCheckFunc { - return resource.ComposeAggregateTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "resource_group_name", fmt.Sprintf("acctestRG-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "recovery_vault_name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backup.0.frequency", "Weekly"), - resource.TestCheckResourceAttr(resourceName, "backup.0.time", "23:00"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.count", "42"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.weekdays.#", "2"), - ) -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Daily" - time = "23:00" - } - - retention_daily { - count = 10 - } - - retention_weekly { - count = 42 - weekdays = ["Sunday", "Wednesday"] - } - - retention_monthly { - count = 7 - weekdays = ["Sunday", "Wednesday"] - weeks = ["First", "Last"] - } - - retention_yearly { - count = 77 - weekdays = ["Sunday", "Wednesday"] - weeks = ["First", "Last"] - months = ["January", "July"] - } -} -`, template, data.RandomInteger) -} - -func checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeDaily(resourceName string, ri int) resource.TestCheckFunc { - return resource.ComposeAggregateTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "resource_group_name", fmt.Sprintf("acctestRG-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "recovery_vault_name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backup.0.frequency", "Daily"), - resource.TestCheckResourceAttr(resourceName, "backup.0.time", "23:00"), - resource.TestCheckResourceAttr(resourceName, "retention_daily.0.count", "10"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.count", "42"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.weekdays.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.count", "7"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.weekdays.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.weeks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.count", "77"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.weekdays.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.weeks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.months.#", "2"), - ) -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Weekly" - time = "23:00" - weekdays = ["Sunday", "Wednesday", "Friday", "Saturday"] - } - - retention_weekly { - count = 42 - weekdays = ["Sunday", "Wednesday", "Friday", "Saturday"] - } - - retention_monthly { - count = 7 - weekdays = ["Sunday", "Wednesday", "Friday", "Saturday"] - weeks = ["First", "Last"] - } - - retention_yearly { - count = 77 - weekdays = ["Sunday", "Wednesday", "Friday", "Saturday"] - weeks = ["First", "Last"] - months = ["January", "July"] - } -} -`, template, data.RandomInteger) -} - -func checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeekly(resourceName string, ri int) resource.TestCheckFunc { - return resource.ComposeAggregateTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "resource_group_name", fmt.Sprintf("acctestRG-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "recovery_vault_name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backup.0.frequency", "Weekly"), - resource.TestCheckResourceAttr(resourceName, "backup.0.time", "23:00"), - resource.TestCheckResourceAttr(resourceName, "backup.0.weekdays.#", "4"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.count", "42"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.weekdays.#", "4"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.count", "7"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.weekdays.#", "4"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.weeks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.count", "77"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.weekdays.#", "4"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.weeks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.months.#", "2"), - ) -} - -func testAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeeklyPartial(data acceptance.TestData) string { - template := testAccAzureRMRecoveryServicesProtectionPolicyVm_base(data) - return fmt.Sprintf(` -%s - -resource "azurerm_recovery_services_protection_policy_vm" "test" { - name = "acctest-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - - backup { - frequency = "Weekly" - time = "23:00" - weekdays = ["Sunday", "Wednesday", "Friday", "Saturday"] - } - - retention_weekly { - count = 42 - weekdays = ["Sunday", "Wednesday", "Friday"] - } - - retention_monthly { - count = 7 - weekdays = ["Sunday", "Wednesday"] - weeks = ["First", "Last"] - } - - retention_yearly { - count = 77 - weekdays = ["Sunday"] - weeks = ["Last"] - months = ["January"] - } -} -`, template, data.RandomInteger) -} - -func checkAccAzureRMRecoveryServicesProtectionPolicyVm_completeWeeklyPartial(resourceName string, ri int) resource.TestCheckFunc { - return resource.ComposeAggregateTestCheckFunc( - testCheckAzureRMRecoveryServicesProtectionPolicyVmExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "resource_group_name", fmt.Sprintf("acctestRG-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "recovery_vault_name", fmt.Sprintf("acctest-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backup.0.frequency", "Weekly"), - resource.TestCheckResourceAttr(resourceName, "backup.0.time", "23:00"), - resource.TestCheckResourceAttr(resourceName, "backup.0.weekdays.#", "4"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.count", "42"), - resource.TestCheckResourceAttr(resourceName, "retention_weekly.0.weekdays.#", "3"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.count", "7"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.weekdays.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_monthly.0.weeks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.count", "77"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.weekdays.#", "1"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.weeks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "retention_yearly.0.months.#", "1"), - ) -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replicated_vm_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replicated_vm_test.go deleted file mode 100644 index ed035ebfd46e..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replicated_vm_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" -) - -func TestAccAzureRMRecoveryReplicatedVm_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_replicated_vm", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryReplicatedVmDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryReplicatedVm_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryReplicatedVmExists(data.ResourceName), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMRecoveryReplicatedVm_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d-1" - location = "%s" -} - -resource "azurerm_resource_group" "test2" { - name = "acctestRG-recovery-%d-2" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-vault-%d" - location = "${azurerm_resource_group.test2.location}" - resource_group_name = "${azurerm_resource_group.test2.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_fabric" "test1" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric1-%d" - location = "${azurerm_resource_group.test.location}" -} - -resource "azurerm_recovery_services_fabric" "test2" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-fabric2-%d" - location = "${azurerm_resource_group.test2.location}" - depends_on = ["azurerm_recovery_services_fabric.test1"] -} - -resource "azurerm_recovery_services_protection_container" "test1" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - name = "acctest-protection-cont1-%d" -} - -resource "azurerm_recovery_services_protection_container" "test2" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test2.name}" - name = "acctest-protection-cont2-%d" -} - -resource "azurerm_recovery_services_replication_policy" "test" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-policy-%d" - recovery_point_retention_in_minutes = "${24 * 60}" - application_consistent_snapshot_frequency_in_minutes = "${4 * 60}" -} - -resource "azurerm_recovery_services_protection_container_mapping" "test" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - recovery_source_protection_container_name = "${azurerm_recovery_services_protection_container.test1.name}" - recovery_target_protection_container_id = "${azurerm_recovery_services_protection_container.test2.id}" - recovery_replication_policy_id = "${azurerm_recovery_services_replication_policy.test.id}" - name = "mapping-%d" -} - -resource "azurerm_virtual_network" "test1" { - name = "net-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - address_space = ["192.168.1.0/24"] - location = "${azurerm_recovery_services_fabric.test1.location}" -} -resource "azurerm_subnet" "test1" { - name = "snet-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test1.name}" - address_prefix = "192.168.1.0/24" -} - - -resource "azurerm_virtual_network" "test2" { - name = "net-%d" - resource_group_name = "${azurerm_resource_group.test2.name}" - address_space = ["192.168.2.0/24"] - location = "${azurerm_recovery_services_fabric.test2.location}" -} - -resource "azurerm_recovery_network_mapping" "test" { - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "mapping-%d" - source_recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - target_recovery_fabric_name = "${azurerm_recovery_services_fabric.test2.name}" - source_network_id = "${azurerm_virtual_network.test1.id}" - target_network_id = "${azurerm_virtual_network.test2.id}" -} - -resource "azurerm_network_interface" "test" { - name = "vm-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "vm-%d" - subnet_id = "${azurerm_subnet.test1.id}" - private_ip_address_allocation = "Dynamic" - } -} - -resource "azurerm_virtual_machine" "test" { - name = "vm-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - - vm_size = "Standard_B1s" - - storage_image_reference { - publisher = "OpenLogic" - offer = "CentOS" - sku = "7.5" - version = "latest" - } - - storage_os_disk { - name = "disk-%d" - os_type = "Linux" - caching = "ReadWrite" - create_option = "FromImage" - managed_disk_type = "Premium_LRS" - } - - os_profile { - admin_username = "testadmin" - admin_password = "Password1234!" - computer_name = "vm-%d" - } - - os_profile_linux_config { - disable_password_authentication = false - - } - network_interface_ids = ["${azurerm_network_interface.test.id}"] -} - -resource "azurerm_storage_account" "test" { - name = "acct%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - account_tier = "Standard" - account_replication_type = "LRS" -} - -resource "azurerm_recovery_replicated_vm" "test" { - name = "repl-%d" - resource_group_name = "${azurerm_resource_group.test2.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - source_vm_id = "${azurerm_virtual_machine.test.id}" - source_recovery_fabric_name = "${azurerm_recovery_services_fabric.test1.name}" - recovery_replication_policy_id = "${azurerm_recovery_services_replication_policy.test.id}" - source_recovery_protection_container_name = "${azurerm_recovery_services_protection_container.test1.name}" - - target_resource_group_id = "${azurerm_resource_group.test2.id}" - target_recovery_fabric_id = "${azurerm_recovery_services_fabric.test2.id}" - target_recovery_protection_container_id = "${azurerm_recovery_services_protection_container.test2.id}" - - managed_disk { - disk_id = "${azurerm_virtual_machine.test.storage_os_disk.0.managed_disk_id}" - staging_storage_account_id = "${azurerm_storage_account.test.id}" - target_resource_group_id = "${azurerm_resource_group.test2.id}" - target_disk_type = "Premium_LRS" - target_replica_disk_type = "Premium_LRS" - } - depends_on = ["azurerm_recovery_services_protection_container_mapping.test", "azurerm_recovery_network_mapping.test"] -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.Locations.Secondary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) -} - -func testCheckAzureRMRecoveryReplicatedVmExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - state, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroupName := state.Primary.Attributes["resource_group_name"] - vaultName := state.Primary.Attributes["recovery_vault_name"] - fabricName := state.Primary.Attributes["source_recovery_fabric_name"] - protectionContainerName := state.Primary.Attributes["source_recovery_protection_container_name"] - replicationName := state.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ReplicationMigrationItemsClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, protectionContainerName, replicationName) - if err != nil { - return fmt.Errorf("Bad: Get on RecoveryServices.ReplicationMigrationItemsClient: %+v", err) - } - - if resp.Response.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Recovery Services Replicated VM: %q does not exist", fabricName) - } - - return nil - } -} - -func testCheckAzureRMRecoveryReplicatedVmDestroy(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_replicated_vm" { - continue - } - - resourceGroupName := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - fabricName := rs.Primary.Attributes["source_recovery_fabric_name"] - protectionContainerName := rs.Primary.Attributes["source_recovery_protection_container_name"] - replicationName := rs.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ReplicationMigrationItemsClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, fabricName, protectionContainerName, replicationName) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Recovery Services Replicated VM still exists:\n%#v", resp.Properties) - } - } - - return nil -} diff --git a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replication_policy_test.go b/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replication_policy_test.go deleted file mode 100644 index a414f13e7aa1..000000000000 --- a/azurerm/internal/services/recoveryservices/tests/resource_arm_recovery_services_replication_policy_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package tests - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" -) - -func TestAccAzureRMRecoveryReplicationPolicy_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_recovery_services_replication_policy", "test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acceptance.PreCheck(t) }, - Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMRecoveryReplicationPolicyDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMRecoveryReplicationPolicy_basic(data), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRecoveryReplicationPolicyExists(data.ResourceName), - ), - }, - data.ImportStep(), - }, - }) -} - -func testAccAzureRMRecoveryReplicationPolicy_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-recovery-%d" - location = "%s" -} - -resource "azurerm_recovery_services_vault" "test" { - name = "acctest-vault-%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - soft_delete_enabled = false -} - -resource "azurerm_recovery_services_replication_policy" "test" { - resource_group_name = "${azurerm_resource_group.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" - name = "acctest-policy-%d" - recovery_point_retention_in_minutes = "${24 * 60}" - application_consistent_snapshot_frequency_in_minutes = "${4 * 60}" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) -} - -func testCheckAzureRMRecoveryReplicationPolicyExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - // Ensure we have enough information in state to look up in API - state, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - resourceGroupName := state.Primary.Attributes["resource_group_name"] - vaultName := state.Primary.Attributes["recovery_vault_name"] - policyName := state.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ReplicationPoliciesClient(resourceGroupName, vaultName) - - resp, err := client.Get(ctx, policyName) - if err != nil { - return fmt.Errorf("Bad: Get on RecoveryServices.ReplicationPoliciesClient: %+v", err) - } - - if resp.Response.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Replication Policies: %q does not exist", policyName) - } - - return nil - } -} - -func testCheckAzureRMRecoveryReplicationPolicyDestroy(s *terraform.State) error { - ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_recovery_services_replication_policy" { - continue - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - vaultName := rs.Primary.Attributes["recovery_vault_name"] - policyName := rs.Primary.Attributes["name"] - - client := acceptance.AzureProvider.Meta().(*clients.Client).RecoveryServices.ReplicationPoliciesClient(resourceGroup, vaultName) - - resp, err := client.Get(ctx, policyName) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Replication Policy still exists:\n%#v", resp.Properties) - } - } - - return nil -} diff --git a/examples/vm-scale-set/virtual_machine_scale_set/autoscale/main.tf b/examples/vm-scale-set/virtual_machine_scale_set/autoscale/main.tf index d68d242e8cad..4e73608e82ff 100644 --- a/examples/vm-scale-set/virtual_machine_scale_set/autoscale/main.tf +++ b/examples/vm-scale-set/virtual_machine_scale_set/autoscale/main.tf @@ -69,7 +69,7 @@ resource "azurerm_virtual_machine_scale_set" "example" { } } -resource "azurerm_autoscale_setting" "example" { +resource "azurerm_monitor_autoscale_setting" "example" { name = "autoscale-cpu" target_resource_id = "${azurerm_virtual_machine_scale_set.example.id}" location = "${azurerm_resource_group.example.location}" diff --git a/website/azurerm.erb b/website/azurerm.erb index 13e50d7b1078..8b0465af594b 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -123,19 +123,19 @@
  • - azurerm_batch_account + azurerm_backup_protection_policy_vm
  • - azurerm_batch_certificate + azurerm_batch_account
  • - azurerm_batch_pool + azurerm_batch_certificate
  • - azurerm_builtin_role_definition + azurerm_batch_pool
  • @@ -378,10 +378,6 @@ azurerm_private_endpoint_connection
  • -
  • - azurerm_private_link_endpoint_connection -
  • -
  • azurerm_private_link_service
  • @@ -406,10 +402,6 @@ azurerm_recovery_services_vault -
  • - azurerm_recovery_services_protection_policy_vm -
  • -
  • azurerm_redis_cache
  • @@ -1678,10 +1670,6 @@
  • Monitor Resources
  • @@ -1727,22 +1708,10 @@ azurerm_application_security_group -
  • - azurerm_connection_monitor -
  • -
  • azurerm_bastion_host
  • -
  • - azurerm_network_connection_monitor -
  • - -
  • - azurerm_ddos_protection_plan -
  • -
  • azurerm_network_ddos_protection_plan
  • @@ -1851,10 +1820,6 @@ azurerm_private_endpoint -
  • - azurerm_private_link_endpoint -
  • -
  • azurerm_public_ip
  • @@ -2014,38 +1979,10 @@
  • Recovery Services