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_network_ddos_protection_plan_test.go b/azurerm/internal/services/network/tests/resource_arm_network_ddos_protection_plan_test.go index a246d3c33d1b..6777f2a94a65 100644 --- a/azurerm/internal/services/network/tests/resource_arm_network_ddos_protection_plan_test.go +++ b/azurerm/internal/services/network/tests/resource_arm_network_ddos_protection_plan_test.go @@ -25,12 +25,6 @@ func TestAccAzureRMNetworkDDoSProtectionPlan(t *testing.T) { "datasource": { "basic": testAccAzureRMNetworkDDoSProtectionPlanDataSource_basic, }, - "deprecated": { - "basic": testAccAzureRMDDoSProtectionPlan_basic, - "requiresImport": testAccAzureRMDDoSProtectionPlan_requiresImport, - "withTags": testAccAzureRMDDoSProtectionPlan_withTags, - "disappears": testAccAzureRMDDoSProtectionPlan_disappears, - }, } for group, steps := range testCases { diff --git a/azurerm/internal/services/network/tests/resource_arm_network_watcher_test.go b/azurerm/internal/services/network/tests/resource_arm_network_watcher_test.go index 855f58eec336..3160cf96cb17 100644 --- a/azurerm/internal/services/network/tests/resource_arm_network_watcher_test.go +++ b/azurerm/internal/services/network/tests/resource_arm_network_watcher_test.go @@ -28,18 +28,6 @@ func TestAccAzureRMNetworkWatcher(t *testing.T) { "DataSource": { "basic": testAccDataSourceAzureRMNetworkWatcher_basic, }, - "ConnectionMonitorOld": { - "addressBasic": testAccAzureRMConnectionMonitor_addressBasic, - "addressComplete": testAccAzureRMConnectionMonitor_addressComplete, - "addressUpdate": testAccAzureRMConnectionMonitor_addressUpdate, - "vmBasic": testAccAzureRMConnectionMonitor_vmBasic, - "vmComplete": testAccAzureRMConnectionMonitor_vmComplete, - "vmUpdate": testAccAzureRMConnectionMonitor_vmUpdate, - "destinationUpdate": testAccAzureRMConnectionMonitor_destinationUpdate, - "missingDestinationInvalid": testAccAzureRMConnectionMonitor_missingDestination, - "bothDestinationsInvalid": testAccAzureRMConnectionMonitor_conflictingDestinations, - "requiresImport": testAccAzureRMConnectionMonitor_requiresImport, - }, "PacketCaptureOld": { "localDisk": testAccAzureRMPacketCapture_localDisk, "storageAccount": testAccAzureRMPacketCapture_storageAccount, 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_backup_policy_vm.go b/azurerm/internal/services/recoveryservices/data_source_backup_policy_vm.go index e427c0f329c4..626a073105c9 100644 --- a/azurerm/internal/services/recoveryservices/data_source_backup_policy_vm.go +++ b/azurerm/internal/services/recoveryservices/data_source_backup_policy_vm.go @@ -16,7 +16,7 @@ import ( 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 dataSourceArmBackupPolicyVm() *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/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_backup_policy_vm_test.go b/azurerm/internal/services/recoveryservices/tests/data_source_backup_policy_vm_test.go index 53136f3780ce..f2e920c95989 100644 --- a/azurerm/internal/services/recoveryservices/tests/data_source_backup_policy_vm_test.go +++ b/azurerm/internal/services/recoveryservices/tests/data_source_backup_policy_vm_test.go @@ -16,7 +16,7 @@ func TestAccDataSourceAzureRMBackupPolicyVm_basic(t *testing.T) { Providers: acceptance.SupportedProviders, Steps: []resource.TestStep{ { - Config: testAccDataSourceBackupProtectionPolicyVm_basic(data), + Config: testAccDataSourceBackupPolicyVm_basic(data), Check: resource.ComposeTestCheckFunc( testCheckAzureRMBackupProtectionPolicyVmExists(data.ResourceName), resource.TestCheckResourceAttrSet(data.ResourceName, "name"), @@ -29,14 +29,14 @@ func TestAccDataSourceAzureRMBackupPolicyVm_basic(t *testing.T) { }) } -func testAccDataSourceBackupProtectionPolicyVm_basic(data acceptance.TestData) string { +func testAccDataSourceBackupPolicyVm_basic(data acceptance.TestData) string { template := testAccAzureRMBackupProtectionPolicyVM_basicDaily(data) return fmt.Sprintf(` %s data "azurerm_backup_policy_vm" "test" { name = "${azurerm_backup_policy_vm.test.name}" - recovery_vault_name = "${azurerm_recovery_services_vault.test.name}" + recovery_vault_name = "${azurerm_backup_vault.test.name}" resource_group_name = "${azurerm_resource_group.test.name}" } `, template) 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 450524c095bb..e051dae81b23 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -138,10 +138,6 @@ azurerm_batch_pool -