diff --git a/azurerm/internal/services/monitor/action_rule.go b/azurerm/internal/services/monitor/action_rule.go new file mode 100644 index 000000000000..3879bfef7fd2 --- /dev/null +++ b/azurerm/internal/services/monitor/action_rule.go @@ -0,0 +1,302 @@ +package monitor + +import ( + "fmt" + + "github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +const ( + scheduleDateLayout = "01/02/2006" + scheduleTimeLayout = "15:04:05" + scheduleDateTimeLayout = scheduleDateLayout + " " + scheduleTimeLayout +) + +var weekDays = []string{ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", +} + +var weekDayMap = map[string]int{ + "Sunday": 0, + "Monday": 1, + "Tuesday": 2, + "Wednesday": 3, + "Thursday": 4, + "Friday": 5, + "Saturday": 6, +} + +func schemaActionRuleConditions() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alert_context": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + string(alertsmanagement.Contains), + string(alertsmanagement.DoesNotContain), + }, + nil, + ), + + "alert_rule_id": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + string(alertsmanagement.Contains), + string(alertsmanagement.DoesNotContain), + }, nil, + ), + + "description": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + string(alertsmanagement.Contains), + string(alertsmanagement.DoesNotContain), + }, + nil, + ), + + "monitor": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + }, + []string{ + string(alertsmanagement.Fired), + string(alertsmanagement.Resolved), + }, + ), + + "monitor_service": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + }, + // the supported type list is not consistent with the swagger and sdk + // https://github.com/Azure/azure-rest-api-specs/issues/9076 + // directly use string constant + []string{ + "ActivityLog Administrative", + "ActivityLog Autoscale", + "ActivityLog Policy", + "ActivityLog Recommendation", + "ActivityLog Security", + "Application Insights", + "Azure Backup", + "Data Box Edge", + "Data Box Gateway", + "Health Platform", + "Log Analytics", + "Platform", + "Resource Health", + }, + ), + + "severity": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + }, + []string{ + string(alertsmanagement.Sev0), + string(alertsmanagement.Sev1), + string(alertsmanagement.Sev2), + string(alertsmanagement.Sev3), + string(alertsmanagement.Sev4), + }, + ), + + "target_resource_type": schemaActionRuleCondition( + []string{ + string(alertsmanagement.Equals), + string(alertsmanagement.NotEquals), + }, + nil, + ), + }, + }, + } +} + +func schemaActionRuleCondition(operatorValidateItems, valuesValidateItems []string) *schema.Schema { + operatorValidateFunc := validation.StringIsNotEmpty + valuesValidateFunc := validation.StringIsNotEmpty + if len(operatorValidateItems) > 0 { + operatorValidateFunc = validation.StringInSlice(operatorValidateItems, false) + } + if len(valuesValidateItems) > 0 { + valuesValidateFunc = validation.StringInSlice(valuesValidateItems, false) + } + + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "operator": { + Type: schema.TypeString, + Required: true, + ValidateFunc: operatorValidateFunc, + }, + + "values": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: valuesValidateFunc, + }, + }, + }, + }, + } +} + +func expandArmActionRuleCondition(input []interface{}) *alertsmanagement.Condition { + if len(input) == 0 { + return nil + } + + v := input[0].(map[string]interface{}) + return &alertsmanagement.Condition{ + Operator: alertsmanagement.Operator(v["operator"].(string)), + Values: utils.ExpandStringSlice(v["values"].(*schema.Set).List()), + } +} + +func expandArmActionRuleScope(input []interface{}) *alertsmanagement.Scope { + if len(input) == 0 { + return nil + } + + v := input[0].(map[string]interface{}) + return &alertsmanagement.Scope{ + ScopeType: alertsmanagement.ScopeType(v["type"].(string)), + Values: utils.ExpandStringSlice(v["resource_ids"].(*schema.Set).List()), + } +} + +func expandArmActionRuleConditions(input []interface{}) *alertsmanagement.Conditions { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + return &alertsmanagement.Conditions{ + AlertContext: expandArmActionRuleCondition(v["alert_context"].([]interface{})), + AlertRuleID: expandArmActionRuleCondition(v["alert_rule_id"].([]interface{})), + Description: expandArmActionRuleCondition(v["description"].([]interface{})), + MonitorCondition: expandArmActionRuleCondition(v["monitor"].([]interface{})), + MonitorService: expandArmActionRuleCondition(v["monitor_service"].([]interface{})), + Severity: expandArmActionRuleCondition(v["severity"].([]interface{})), + TargetResourceType: expandArmActionRuleCondition(v["target_resource_type"].([]interface{})), + } +} + +func flattenArmActionRuleCondition(input *alertsmanagement.Condition) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + var operator string + if input.Operator != "" { + operator = string(input.Operator) + } + return []interface{}{ + map[string]interface{}{ + "operator": operator, + "values": utils.FlattenStringSlice(input.Values), + }, + } +} + +func flattenArmActionRuleScope(input *alertsmanagement.Scope) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + var scopeType alertsmanagement.ScopeType + if input.ScopeType != "" { + scopeType = input.ScopeType + } + return []interface{}{ + map[string]interface{}{ + "type": scopeType, + "resource_ids": utils.FlattenStringSlice(input.Values), + }, + } +} + +func flattenArmActionRuleConditions(input *alertsmanagement.Conditions) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + return []interface{}{ + map[string]interface{}{ + "alert_context": flattenArmActionRuleCondition(input.AlertContext), + "alert_rule_id": flattenArmActionRuleCondition(input.AlertRuleID), + "description": flattenArmActionRuleCondition(input.Description), + "monitor": flattenArmActionRuleCondition(input.MonitorCondition), + "monitor_service": flattenArmActionRuleCondition(input.MonitorService), + "severity": flattenArmActionRuleCondition(input.Severity), + "target_resource_type": flattenArmActionRuleCondition(input.TargetResourceType), + }, + } +} + +func importMonitorActionRule(actionRuleType alertsmanagement.Type) func(d *schema.ResourceData, meta interface{}) (data []*schema.ResourceData, err error) { + return func(d *schema.ResourceData, meta interface{}) (data []*schema.ResourceData, err error) { + id, err := parse.ActionRuleID(d.Id()) + if err != nil { + return nil, err + } + + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + actionRule, err := client.GetByName(ctx, id.ResourceGroup, id.Name) + if err != nil { + return nil, fmt.Errorf("retrieving Monitor Action Rule %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + + if actionRule.Properties == nil { + return nil, fmt.Errorf("retrieving Monitor Action Rule %q (Resource Group %q): `properties` was nil", id.Name, id.ResourceGroup) + } + + var t alertsmanagement.Type + switch actionRule.Properties.(type) { + case alertsmanagement.Suppression: + t = alertsmanagement.TypeSuppression + case alertsmanagement.ActionGroup: + t = alertsmanagement.TypeActionGroup + case alertsmanagement.Diagnostics: + t = alertsmanagement.TypeDiagnostics + } + + if t != actionRuleType { + return nil, fmt.Errorf("Monitor Action Rule has mismatched kind, expected: %q, got %q", actionRuleType, t) + } + + return []*schema.ResourceData{d}, nil + } +} diff --git a/azurerm/internal/services/monitor/client/client.go b/azurerm/internal/services/monitor/client/client.go index 15a3ddd0734a..6903f232bd96 100644 --- a/azurerm/internal/services/monitor/client/client.go +++ b/azurerm/internal/services/monitor/client/client.go @@ -1,6 +1,7 @@ package client import ( + "github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement" "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/common" ) @@ -9,6 +10,9 @@ type Client struct { // Autoscale Settings AutoscaleSettingsClient *insights.AutoscaleSettingsClient + // alerts management + ActionRulesClient *alertsmanagement.ActionRulesClient + // Monitor ActionGroupsClient *insights.ActionGroupsClient ActivityLogAlertsClient *insights.ActivityLogAlertsClient @@ -24,6 +28,9 @@ func NewClient(o *common.ClientOptions) *Client { AutoscaleSettingsClient := insights.NewAutoscaleSettingsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&AutoscaleSettingsClient.Client, o.ResourceManagerAuthorizer) + ActionRulesClient := alertsmanagement.NewActionRulesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&ActionRulesClient.Client, o.ResourceManagerAuthorizer) + ActionGroupsClient := insights.NewActionGroupsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&ActionGroupsClient.Client, o.ResourceManagerAuthorizer) @@ -50,6 +57,7 @@ func NewClient(o *common.ClientOptions) *Client { return &Client{ AutoscaleSettingsClient: &AutoscaleSettingsClient, + ActionRulesClient: &ActionRulesClient, ActionGroupsClient: &ActionGroupsClient, ActivityLogAlertsClient: &ActivityLogAlertsClient, AlertRulesClient: &AlertRulesClient, diff --git a/azurerm/internal/services/monitor/monitor_action_rule_action_group_resource.go b/azurerm/internal/services/monitor/monitor_action_rule_action_group_resource.go new file mode 100644 index 000000000000..b175770d5bc6 --- /dev/null +++ b/azurerm/internal/services/monitor/monitor_action_rule_action_group_resource.go @@ -0,0 +1,211 @@ +package monitor + +import ( + "fmt" + "log" + "time" + + "github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement" + "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/location" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmMonitorActionRuleActionGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceArmMonitorActionRuleActionGroupCreateUpdate, + Read: resourceArmMonitorActionRuleActionGroupRead, + Update: resourceArmMonitorActionRuleActionGroupCreateUpdate, + Delete: resourceArmMonitorActionRuleActionGroupDelete, + + 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), + }, + + Importer: azSchema.ValidateResourceIDPriorToImportThen(func(id string) error { + _, err := parse.ActionRuleID(id) + return err + }, importMonitorActionRule(alertsmanagement.TypeActionGroup)), + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.ActionRuleName, + }, + + "resource_group_name": azure.SchemaResourceGroupName(), + + "action_group_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.ActionGroupID, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "condition": schemaActionRuleConditions(), + + "scope": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(alertsmanagement.ScopeTypeResourceGroup), + string(alertsmanagement.ScopeTypeResource), + }, false), + }, + + "resource_ids": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: azure.ValidateResourceID, + }, + }, + }, + }, + }, + + "tags": tags.Schema(), + }, + } +} + +func resourceArmMonitorActionRuleActionGroupCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + resourceGroup := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + + if d.IsNewResource() { + existing, err := client.GetByName(ctx, resourceGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for presence of existing Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + if existing.ID != nil && *existing.ID != "" { + return tf.ImportAsExistsError("azurerm_monitor_action_rule_action_group", *existing.ID) + } + } + + actionRuleStatus := alertsmanagement.Enabled + if !d.Get("enabled").(bool) { + actionRuleStatus = alertsmanagement.Disabled + } + + actionRule := alertsmanagement.ActionRule{ + // the location is always global from the portal + Location: utils.String(location.Normalize("Global")), + Properties: &alertsmanagement.ActionGroup{ + ActionGroupID: utils.String(d.Get("action_group_id").(string)), + Scope: expandArmActionRuleScope(d.Get("scope").([]interface{})), + Conditions: expandArmActionRuleConditions(d.Get("condition").([]interface{})), + Description: utils.String(d.Get("description").(string)), + Status: actionRuleStatus, + Type: alertsmanagement.TypeActionGroup, + }, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + } + + if _, err := client.CreateUpdate(ctx, resourceGroup, name, actionRule); err != nil { + return fmt.Errorf("creating/updatinge Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + resp, err := client.GetByName(ctx, resourceGroup, name) + if err != nil { + return fmt.Errorf("retrieving Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + if resp.ID == nil || *resp.ID == "" { + return fmt.Errorf("empty or nil ID returned for Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.SetId(*resp.ID) + return resourceArmMonitorActionRuleActionGroupRead(d, meta) +} + +func resourceArmMonitorActionRuleActionGroupRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.ActionRuleID(d.Id()) + if err != nil { + return err + } + + resp, err := client.GetByName(ctx, id.ResourceGroup, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] Action Rule %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("retrieving Monitor ActionRule %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", id.ResourceGroup) + if resp.Properties != nil { + props, _ := resp.Properties.AsActionGroup() + d.Set("description", props.Description) + d.Set("action_group_id", props.ActionGroupID) + d.Set("enabled", props.Status == alertsmanagement.Enabled) + if err := d.Set("scope", flattenArmActionRuleScope(props.Scope)); err != nil { + return fmt.Errorf("setting scope: %+v", err) + } + if err := d.Set("condition", flattenArmActionRuleConditions(props.Conditions)); err != nil { + return fmt.Errorf("setting condition: %+v", err) + } + } + + return tags.FlattenAndSet(d, resp.Tags) +} + +func resourceArmMonitorActionRuleActionGroupDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.ActionRuleID(d.Id()) + if err != nil { + return err + } + + if _, err := client.Delete(ctx, id.ResourceGroup, id.Name); err != nil { + return fmt.Errorf("deleting monitor ActionRule %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + return nil +} diff --git a/azurerm/internal/services/monitor/monitor_action_rule_suppression_resource.go b/azurerm/internal/services/monitor/monitor_action_rule_suppression_resource.go new file mode 100644 index 000000000000..371954c400a3 --- /dev/null +++ b/azurerm/internal/services/monitor/monitor_action_rule_suppression_resource.go @@ -0,0 +1,400 @@ +package monitor + +import ( + "fmt" + "log" + "time" + + "github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement" + "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/location" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmMonitorActionRuleSuppression() *schema.Resource { + return &schema.Resource{ + Create: resourceArmMonitorActionRuleSuppressionCreateUpdate, + Read: resourceArmMonitorActionRuleSuppressionRead, + Update: resourceArmMonitorActionRuleSuppressionCreateUpdate, + Delete: resourceArmMonitorActionRuleSuppressionDelete, + + 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), + }, + + Importer: azSchema.ValidateResourceIDPriorToImportThen(func(id string) error { + _, err := parse.ActionRuleID(id) + return err + }, importMonitorActionRule(alertsmanagement.TypeSuppression)), + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.ActionRuleName, + }, + + "resource_group_name": azure.SchemaResourceGroupName(), + + "suppression": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "recurrence_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(alertsmanagement.Always), + string(alertsmanagement.Once), + string(alertsmanagement.Daily), + string(alertsmanagement.Weekly), + string(alertsmanagement.Monthly), + }, false), + }, + + "schedule": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "start_date_utc": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.IsRFC3339Time, + }, + + "end_date_utc": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.IsRFC3339Time, + }, + + "recurrence_weekly": { + Type: schema.TypeSet, + Optional: true, + MinItems: 1, + ConflictsWith: []string{"suppression.0.schedule.0.recurrence_monthly"}, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.IsDayOfTheWeek(false), + }, + }, + + "recurrence_monthly": { + Type: schema.TypeSet, + Optional: true, + MinItems: 1, + ConflictsWith: []string{"suppression.0.schedule.0.recurrence_weekly"}, + Elem: &schema.Schema{ + Type: schema.TypeInt, + ValidateFunc: validation.IntBetween(1, 31), + }, + }, + }, + }, + }, + }, + }, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "condition": schemaActionRuleConditions(), + + "scope": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(alertsmanagement.ScopeTypeResourceGroup), + string(alertsmanagement.ScopeTypeResource), + }, false), + }, + + "resource_ids": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: azure.ValidateResourceID, + }, + }, + }, + }, + }, + + "tags": tags.Schema(), + }, + } +} + +func resourceArmMonitorActionRuleSuppressionCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + resourceGroup := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + + if d.IsNewResource() { + existing, err := client.GetByName(ctx, resourceGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for present of existing Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + if existing.ID != nil && *existing.ID != "" { + return tf.ImportAsExistsError("azurerm_monitor_action_rule_suppression", *existing.ID) + } + } + + actionRuleStatus := alertsmanagement.Enabled + if !d.Get("enabled").(bool) { + actionRuleStatus = alertsmanagement.Disabled + } + + suppressionConfig, err := expandArmActionRuleSuppressionConfig(d.Get("suppression").([]interface{})) + if err != nil { + return err + } + + actionRule := alertsmanagement.ActionRule{ + // the location is always global from the portal + Location: utils.String(location.Normalize("Global")), + Properties: &alertsmanagement.Suppression{ + SuppressionConfig: suppressionConfig, + Scope: expandArmActionRuleScope(d.Get("scope").([]interface{})), + Conditions: expandArmActionRuleConditions(d.Get("condition").([]interface{})), + Description: utils.String(d.Get("description").(string)), + Status: actionRuleStatus, + Type: alertsmanagement.TypeSuppression, + }, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + } + + if _, err := client.CreateUpdate(ctx, resourceGroup, name, actionRule); err != nil { + return fmt.Errorf("creating/updatinge Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + resp, err := client.GetByName(ctx, resourceGroup, name) + if err != nil { + return fmt.Errorf("retrieving Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + if resp.ID == nil || *resp.ID == "" { + return fmt.Errorf("empty or nil ID returned for Monitor ActionRule %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.SetId(*resp.ID) + return resourceArmMonitorActionRuleSuppressionRead(d, meta) +} + +func resourceArmMonitorActionRuleSuppressionRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.ActionRuleID(d.Id()) + if err != nil { + return err + } + + resp, err := client.GetByName(ctx, id.ResourceGroup, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] Action Rule %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("retrieving monitor ActionRule %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", id.ResourceGroup) + if resp.Properties != nil { + props, _ := resp.Properties.AsSuppression() + d.Set("description", props.Description) + d.Set("enabled", props.Status == alertsmanagement.Enabled) + if err := d.Set("suppression", flattenArmActionRuleSuppression(props.SuppressionConfig)); err != nil { + return fmt.Errorf("setting suppression: %+v", err) + } + if err := d.Set("scope", flattenArmActionRuleScope(props.Scope)); err != nil { + return fmt.Errorf("setting scope: %+v", err) + } + if err := d.Set("condition", flattenArmActionRuleConditions(props.Conditions)); err != nil { + return fmt.Errorf("setting condition: %+v", err) + } + } + + return tags.FlattenAndSet(d, resp.Tags) +} + +func resourceArmMonitorActionRuleSuppressionDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Monitor.ActionRulesClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.ActionRuleID(d.Id()) + if err != nil { + return err + } + + if _, err := client.Delete(ctx, id.ResourceGroup, id.Name); err != nil { + return fmt.Errorf("deleting monitor ActionRule %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + return nil +} + +func expandArmActionRuleSuppressionConfig(input []interface{}) (*alertsmanagement.SuppressionConfig, error) { + if len(input) == 0 { + return nil, nil + } + v := input[0].(map[string]interface{}) + recurrenceType := alertsmanagement.SuppressionType(v["recurrence_type"].(string)) + schedule, err := expandArmActionRuleSuppressionSchedule(v["schedule"].([]interface{}), recurrenceType) + if err != nil { + return nil, err + } + if recurrenceType != alertsmanagement.Always && schedule == nil { + return nil, fmt.Errorf("`schedule` block must be set when `recurrence_type` is Once, Daily, Weekly or Monthly.") + } + return &alertsmanagement.SuppressionConfig{ + RecurrenceType: recurrenceType, + Schedule: schedule, + }, nil +} + +func expandArmActionRuleSuppressionSchedule(input []interface{}, suppressionType alertsmanagement.SuppressionType) (*alertsmanagement.SuppressionSchedule, error) { + if len(input) == 0 { + return nil, nil + } + v := input[0].(map[string]interface{}) + + var recurrence []interface{} + switch suppressionType { + case alertsmanagement.Weekly: + if recurrenceWeekly, ok := v["recurrence_weekly"]; ok { + recurrence = expandArmActionRuleSuppressionScheduleRecurrenceWeekly(recurrenceWeekly.(*schema.Set).List()) + } + if len(recurrence) == 0 { + return nil, fmt.Errorf("`recurrence_weekly` must be set and should have at least one element when `recurrence_type` is Weekly.") + } + case alertsmanagement.Monthly: + if recurrenceMonthly, ok := v["recurrence_monthly"]; ok { + recurrence = recurrenceMonthly.(*schema.Set).List() + } + if len(recurrence) == 0 { + return nil, fmt.Errorf("`recurrence_monthly` must be set and should have at least one element when `recurrence_type` is Monthly.") + } + } + + startDateUTC, _ := time.Parse(time.RFC3339, v["start_date_utc"].(string)) + endDateUTC, _ := time.Parse(time.RFC3339, v["end_date_utc"].(string)) + return &alertsmanagement.SuppressionSchedule{ + StartDate: utils.String(startDateUTC.Format(scheduleDateLayout)), + EndDate: utils.String(endDateUTC.Format(scheduleDateLayout)), + StartTime: utils.String(startDateUTC.Format(scheduleTimeLayout)), + EndTime: utils.String(endDateUTC.Format(scheduleTimeLayout)), + RecurrenceValues: utils.ExpandInt32Slice(recurrence), + }, nil +} + +func expandArmActionRuleSuppressionScheduleRecurrenceWeekly(input []interface{}) []interface{} { + result := make([]interface{}, 0, len(input)) + for _, v := range input { + result = append(result, weekDayMap[v.(string)]) + } + return result +} + +func flattenArmActionRuleSuppression(input *alertsmanagement.SuppressionConfig) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + var recurrenceType alertsmanagement.SuppressionType + if input.RecurrenceType != "" { + recurrenceType = input.RecurrenceType + } + return []interface{}{ + map[string]interface{}{ + "recurrence_type": string(recurrenceType), + "schedule": flattenArmActionRuleSuppressionSchedule(input.Schedule, recurrenceType), + }, + } +} + +func flattenArmActionRuleSuppressionSchedule(input *alertsmanagement.SuppressionSchedule, recurrenceType alertsmanagement.SuppressionType) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + startDateUTCStr := "" + endDateUTCStr := "" + recurrenceWeekly := []interface{}{} + recurrenceMonthly := []interface{}{} + + if input.StartDate != nil && input.StartTime != nil { + date, _ := time.ParseInLocation(scheduleDateTimeLayout, fmt.Sprintf("%s %s", *input.StartDate, *input.StartTime), time.UTC) + startDateUTCStr = date.Format(time.RFC3339) + } + if input.EndDate != nil && input.EndTime != nil { + date, _ := time.ParseInLocation(scheduleDateTimeLayout, fmt.Sprintf("%s %s", *input.EndDate, *input.EndTime), time.UTC) + endDateUTCStr = date.Format(time.RFC3339) + } + + if recurrenceType == alertsmanagement.Weekly { + recurrenceWeekly = flattenArmActionRuleSuppressionScheduleRecurrenceWeekly(input.RecurrenceValues) + } + if recurrenceType == alertsmanagement.Monthly { + recurrenceMonthly = utils.FlattenInt32Slice(input.RecurrenceValues) + } + return []interface{}{ + map[string]interface{}{ + "start_date_utc": startDateUTCStr, + "end_date_utc": endDateUTCStr, + "recurrence_weekly": recurrenceWeekly, + "recurrence_monthly": recurrenceMonthly, + }, + } +} + +func flattenArmActionRuleSuppressionScheduleRecurrenceWeekly(input *[]int32) []interface{} { + result := make([]interface{}, 0) + if input != nil { + for _, item := range *input { + result = append(result, weekDays[int(item)]) + } + } + return result +} diff --git a/azurerm/internal/services/monitor/parse/monitor_action_group.go b/azurerm/internal/services/monitor/parse/monitor_action_group.go new file mode 100644 index 000000000000..60570e71ae86 --- /dev/null +++ b/azurerm/internal/services/monitor/parse/monitor_action_group.go @@ -0,0 +1,33 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type ActionGroupId struct { + ResourceGroup string + Name string +} + +func ActionGroupID(input string) (*ActionGroupId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("parsing Action Group ID %q: %+v", input, err) + } + + actionGroup := ActionGroupId{ + ResourceGroup: id.ResourceGroup, + } + + if actionGroup.Name, err = id.PopSegment("actionGroups"); err != nil { + return nil, fmt.Errorf("parsing Action Group ID %q: %+v", input, err) + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, fmt.Errorf("parsing Action Group ID %q: %+v", input, err) + } + + return &actionGroup, nil +} diff --git a/azurerm/internal/services/monitor/parse/monitor_action_group_test.go b/azurerm/internal/services/monitor/parse/monitor_action_group_test.go new file mode 100644 index 000000000000..1e655574e625 --- /dev/null +++ b/azurerm/internal/services/monitor/parse/monitor_action_group_test.go @@ -0,0 +1,73 @@ +package parse + +import ( + "testing" +) + +func TestActionGroupId(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *ActionGroupId + }{ + { + Name: "Empty", + Input: "", + Expected: nil, + }, + { + Name: "No Resource Groups Segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No Resource Groups Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/", + Expected: nil, + }, + { + Name: "Missing Action Group Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/microsoft.insights/actionGroups/", + Expected: nil, + }, + { + Name: "Action Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/microsoft.insights/actionGroups/actionGroup1", + Expected: &ActionGroupId{ + Name: "actionGroup1", + ResourceGroup: "resGroup1", + }, + }, + { + Name: "Wrong Casing", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/microsoft.insights/actiongroups/actionGroup1", + Expected: nil, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := ActionGroupID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/monitor/parse/monitor_action_rule.go b/azurerm/internal/services/monitor/parse/monitor_action_rule.go new file mode 100644 index 000000000000..749511576fad --- /dev/null +++ b/azurerm/internal/services/monitor/parse/monitor_action_rule.go @@ -0,0 +1,31 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type ActionRuleId struct { + ResourceGroup string + Name string +} + +func ActionRuleID(input string) (*ActionRuleId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("parsing Action Rule ID %q: %+v", input, err) + } + + actionRule := ActionRuleId{ + ResourceGroup: id.ResourceGroup, + } + if actionRule.Name, err = id.PopSegment("actionRules"); err != nil { + return nil, fmt.Errorf("parsing Action Rule ID %q: %+v", input, err) + } + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, fmt.Errorf("parsing ActionRule ID %q: %+v", input, err) + } + + return &actionRule, nil +} diff --git a/azurerm/internal/services/monitor/parse/monitor_action_rule_test.go b/azurerm/internal/services/monitor/parse/monitor_action_rule_test.go new file mode 100644 index 000000000000..81c518058a17 --- /dev/null +++ b/azurerm/internal/services/monitor/parse/monitor_action_rule_test.go @@ -0,0 +1,72 @@ +package parse + +import ( + "testing" +) + +func TestActionRuleID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *ActionRuleId + }{ + { + Name: "Empty", + Input: "", + Expected: nil, + }, + { + Name: "No Resource Groups Segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No Resource Groups Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/", + Expected: nil, + }, + { + Name: "Missing Action Rule Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.AlertsManagement/actionRules/", + Expected: nil, + }, + { + Name: "Action Rule ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.AlertsManagement/actionRules/actionRule1", + Expected: &ActionRuleId{ + Name: "actionRule1", + ResourceGroup: "resGroup1", + }, + }, + { + Name: "Wrong Casing", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.AlertsManagement/ActionRules/actionRule1", + Expected: nil, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q..", v.Name) + + actual, err := ActionRuleID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + } +} diff --git a/azurerm/internal/services/monitor/registration.go b/azurerm/internal/services/monitor/registration.go index 09676940ddb3..01b0ff1bceed 100644 --- a/azurerm/internal/services/monitor/registration.go +++ b/azurerm/internal/services/monitor/registration.go @@ -33,6 +33,8 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ "azurerm_monitor_autoscale_setting": resourceArmMonitorAutoScaleSetting(), "azurerm_monitor_action_group": resourceArmMonitorActionGroup(), + "azurerm_monitor_action_rule_action_group": resourceArmMonitorActionRuleActionGroup(), + "azurerm_monitor_action_rule_suppression": resourceArmMonitorActionRuleSuppression(), "azurerm_monitor_activity_log_alert": resourceArmMonitorActivityLogAlert(), "azurerm_monitor_diagnostic_setting": resourceArmMonitorDiagnosticSetting(), "azurerm_monitor_log_profile": resourceArmMonitorLogProfile(), diff --git a/azurerm/internal/services/monitor/tests/monitor_action_rule_action_group_resource_test.go b/azurerm/internal/services/monitor/tests/monitor_action_rule_action_group_resource_test.go new file mode 100644 index 000000000000..c98d2d5f08ba --- /dev/null +++ b/azurerm/internal/services/monitor/tests/monitor_action_rule_action_group_resource_test.go @@ -0,0 +1,252 @@ +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/services/monitor/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMMonitorActionRuleActionGroup_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_action_group", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleActionGroup_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleActionGroupExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMonitorActionRuleActionGroup_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_action_group", "test") + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleActionGroup_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleActionGroupExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMMonitorActionRuleActionGroup_requiresImport), + }, + }) +} + +func TestAccAzureRMMonitorActionRuleActionGroup_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_action_group", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleActionGroup_complete(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleActionGroupExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMonitorActionRuleActionGroup_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_action_group", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleActionGroup_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleActionGroupExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMonitorActionRuleActionGroup_complete(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleActionGroupExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMonitorActionRuleActionGroup_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleActionGroupExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func testCheckAzureRMMonitorActionRuleActionGroupExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.ActionRulesClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("can not found Monitor ActionRule: %s", resourceName) + } + id, err := parse.ActionRuleID(rs.Primary.ID) + if err != nil { + return err + } + if resp, err := client.GetByName(ctx, id.ResourceGroup, id.Name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("bad: monitor action_rule %q does not exist", id.Name) + } + return fmt.Errorf("bad: Get on Monitor ActionRulesClient: %+v", err) + } + return nil + } +} + +func testCheckAzureRMMonitorActionRuleActionGroupDestroy(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.ActionRulesClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_monitor_action_rule_action_group" { + continue + } + id, err := parse.ActionRuleID(rs.Primary.ID) + if err != nil { + return err + } + if resp, err := client.GetByName(ctx, id.ResourceGroup, id.Name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("bad: Get on Monitor ActionRulesClient: %+v", err) + } + } + return nil + } + return nil +} + +func testAccAzureRMMonitorActionRuleActionGroup_basic(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleActionGroup_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_action_group" "test" { + name = "acctest-moniter-%d" + resource_group_name = azurerm_resource_group.test.name + action_group_id = azurerm_monitor_action_group.test.id +} +`, template, data.RandomInteger) +} + +func testAccAzureRMMonitorActionRuleActionGroup_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleActionGroup_basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_action_group" "import" { + name = azurerm_monitor_action_rule_action_group.test.name + resource_group_name = azurerm_monitor_action_rule_action_group.test.resource_group_name + action_group_id = azurerm_monitor_action_rule_action_group.test.action_group_id +} +`, template) +} + +func testAccAzureRMMonitorActionRuleActionGroup_complete(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleActionGroup_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_action_group" "test" { + name = "acctest-moniter-%d" + resource_group_name = azurerm_resource_group.test.name + action_group_id = azurerm_monitor_action_group.test.id + enabled = false + description = "actionRule-test" + + scope { + type = "ResourceGroup" + resource_ids = [azurerm_resource_group.test.id] + } + + condition { + alert_context { + operator = "Contains" + values = ["context1", "context2"] + } + + alert_rule_id { + operator = "Contains" + values = ["ruleId1", "ruleId2"] + } + + description { + operator = "DoesNotContain" + values = ["description1", "description2"] + } + + monitor { + operator = "NotEquals" + values = ["Fired"] + } + + monitor_service { + operator = "Equals" + values = ["Data Box Edge", "Data Box Gateway", "Resource Health"] + } + + severity { + operator = "Equals" + values = ["Sev0", "Sev1", "Sev2"] + } + + target_resource_type { + operator = "Equals" + values = ["Microsoft.Compute/VirtualMachines", "microsoft.batch/batchaccounts"] + } + } + + tags = { + ENV = "Test" + } +} +`, template, data.RandomInteger) +} + +func testAccAzureRMMonitorActionRuleActionGroup_template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-monitor-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = azurerm_resource_group.test.name + short_name = "acctestag" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} diff --git a/azurerm/internal/services/monitor/tests/monitor_action_rule_suppression_resource_test.go b/azurerm/internal/services/monitor/tests/monitor_action_rule_suppression_resource_test.go new file mode 100644 index 000000000000..dae02628ef1e --- /dev/null +++ b/azurerm/internal/services/monitor/tests/monitor_action_rule_suppression_resource_test.go @@ -0,0 +1,329 @@ +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/services/monitor/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMMonitorActionRuleSuppression_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_suppression", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleSuppressionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleSuppression_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMonitorActionRuleSuppression_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_suppression", "test") + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleSuppressionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleSuppression_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMMonitorActionRuleSuppression_requiresImport), + }, + }) +} + +func TestAccAzureRMMonitorActionRuleSuppression_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_suppression", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleSuppressionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleSuppression_complete(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMonitorActionRuleSuppression_updateSuppressionConfig(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_monitor_action_rule_suppression", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMonitorActionRuleSuppressionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMonitorActionRuleSuppression_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMonitorActionRuleSuppression_dailyRecurrence(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMonitorActionRuleSuppression_monthlyRecurrence(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMonitorActionRuleSuppression_complete(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMonitorActionRuleSuppression_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionRuleSuppressionExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func testCheckAzureRMMonitorActionRuleSuppressionExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.ActionRulesClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("can not found Monitor ActionRule: %s", resourceName) + } + id, err := parse.ActionRuleID(rs.Primary.ID) + if err != nil { + return err + } + if resp, err := client.GetByName(ctx, id.ResourceGroup, id.Name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("bad: monitor action_rule %q does not exist", id.Name) + } + return fmt.Errorf("bad: Get on Monitor ActionRulesClient: %+v", err) + } + return nil + } +} + +func testCheckAzureRMMonitorActionRuleSuppressionDestroy(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).Monitor.ActionRulesClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_monitor_action_rule_suppression" { + continue + } + id, err := parse.ActionRuleID(rs.Primary.ID) + if err != nil { + return err + } + if resp, err := client.GetByName(ctx, id.ResourceGroup, id.Name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("bad: Get on Monitor ActionRulesClient: %+v", err) + } + } + return nil + } + return nil +} + +func testAccAzureRMMonitorActionRuleSuppression_basic(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleSuppression_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_suppression" "test" { + name = "acctest-moniter-%d" + resource_group_name = azurerm_resource_group.test.name + + suppression { + recurrence_type = "Always" + } +} +`, template, data.RandomInteger) +} + +func testAccAzureRMMonitorActionRuleSuppression_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleSuppression_basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_suppression" "import" { + name = azurerm_monitor_action_rule_suppression.test.name + resource_group_name = azurerm_monitor_action_rule_suppression.test.resource_group_name + + suppression { + recurrence_type = azurerm_monitor_action_rule_suppression.test.suppression.0.recurrence_type + } +} +`, template) +} + +func testAccAzureRMMonitorActionRuleSuppression_complete(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleSuppression_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_suppression" "test" { + name = "acctest-moniter-%d" + resource_group_name = azurerm_resource_group.test.name + enabled = false + description = "actionRule-test" + + scope { + type = "ResourceGroup" + resource_ids = [azurerm_resource_group.test.id] + } + + suppression { + recurrence_type = "Weekly" + + schedule { + start_date_utc = "2019-01-01T01:02:03Z" + end_date_utc = "2019-01-03T15:02:07Z" + + recurrence_weekly = ["Sunday", "Monday", "Friday", "Saturday"] + } + } + + condition { + alert_context { + operator = "Contains" + values = ["context1", "context2"] + } + + alert_rule_id { + operator = "Contains" + values = ["ruleId1", "ruleId2"] + } + + description { + operator = "DoesNotContain" + values = ["description1", "description2"] + } + + monitor { + operator = "NotEquals" + values = ["Fired"] + } + + monitor_service { + operator = "Equals" + values = ["Data Box Edge", "Data Box Gateway", "Resource Health"] + } + + severity { + operator = "Equals" + values = ["Sev0", "Sev1", "Sev2"] + } + + target_resource_type { + operator = "Equals" + values = ["Microsoft.Compute/VirtualMachines", "microsoft.batch/batchaccounts"] + } + } + + tags = { + ENV = "Test" + } +} +`, template, data.RandomInteger) +} + +func testAccAzureRMMonitorActionRuleSuppression_dailyRecurrence(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleSuppression_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_suppression" "test" { + name = "acctest-moniter-%d" + resource_group_name = azurerm_resource_group.test.name + + scope { + type = "ResourceGroup" + resource_ids = [azurerm_resource_group.test.id] + } + + suppression { + recurrence_type = "Daily" + + schedule { + start_date_utc = "2019-01-01T01:02:03Z" + end_date_utc = "2019-01-03T15:02:07Z" + } + } +} +`, template, data.RandomInteger) +} + +func testAccAzureRMMonitorActionRuleSuppression_monthlyRecurrence(data acceptance.TestData) string { + template := testAccAzureRMMonitorActionRuleSuppression_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_monitor_action_rule_suppression" "test" { + name = "acctest-moniter-%d" + resource_group_name = azurerm_resource_group.test.name + + scope { + type = "ResourceGroup" + resource_ids = [azurerm_resource_group.test.id] + } + + suppression { + recurrence_type = "Monthly" + + schedule { + start_date_utc = "2019-01-01T01:02:03Z" + end_date_utc = "2019-01-03T15:02:07Z" + recurrence_monthly = [1, 2, 15, 30, 31] + } + } +} +`, template, data.RandomInteger) +} + +func testAccAzureRMMonitorActionRuleSuppression_template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-monitor-%d" + location = "%s" +} +`, data.RandomInteger, data.Locations.Primary) +} diff --git a/azurerm/internal/services/monitor/validate/monitor_action_group.go b/azurerm/internal/services/monitor/validate/monitor_action_group.go new file mode 100644 index 000000000000..d5b2d956c567 --- /dev/null +++ b/azurerm/internal/services/monitor/validate/monitor_action_group.go @@ -0,0 +1,22 @@ +package validate + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/monitor/parse" +) + +func ActionGroupID(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return + } + + if _, err := parse.ActionGroupID(v); err != nil { + errors = append(errors, fmt.Errorf("validating %q as a resource id: %v", k, err)) + return + } + + return +} diff --git a/azurerm/internal/services/monitor/validate/monitor_action_rule.go b/azurerm/internal/services/monitor/validate/monitor_action_rule.go new file mode 100644 index 000000000000..ddaaf442e613 --- /dev/null +++ b/azurerm/internal/services/monitor/validate/monitor_action_rule.go @@ -0,0 +1,19 @@ +package validate + +import ( + "fmt" + "regexp" +) + +func ActionRuleName(i interface{}, k string) (warning []string, errors []error) { + v, ok := i.(string) + if !ok { + return nil, append(errors, fmt.Errorf("expected type of %s to be string", k)) + } + + if !regexp.MustCompile(`^([a-zA-Z\d])[a-zA-Z\d-_]*$`).MatchString(v) { + errors = append(errors, fmt.Errorf("%s should begin with a letter or number, contain only letters, numbers, underscores and hyphens.", k)) + } + + return +} diff --git a/azurerm/internal/services/monitor/validate/monitor_action_rule_test.go b/azurerm/internal/services/monitor/validate/monitor_action_rule_test.go new file mode 100644 index 000000000000..81c13498ad82 --- /dev/null +++ b/azurerm/internal/services/monitor/validate/monitor_action_rule_test.go @@ -0,0 +1,68 @@ +package validate + +import ( + "testing" +) + +func TestActionRuleName(t *testing.T) { + testData := []struct { + input string + expected bool + }{ + { + // empty + input: "", + expected: false, + }, + { + // basic example, lead by lower case letter + input: "a", + expected: true, + }, + { + // basic example, lead by upper case letter + input: "A", + expected: true, + }, + { + // basic example, lead by number + input: "8", + expected: true, + }, + { + // basic example, contain underscore + input: "a_b", + expected: true, + }, + { + // basic example, end with underscore + input: "ab_", + expected: true, + }, + { + // basic example, end with hyphen + input: "ab-", + expected: true, + }, + { + // can not contain '+' + input: "a+", + expected: false, + }, + { + // can't lead by '-' + input: "-a", + expected: false, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q..", v.input) + + _, errors := ActionRuleName(v.input, "name") + actual := len(errors) == 0 + if v.expected != actual { + t.Fatalf("Expected %t but got %t", v.expected, actual) + } + } +} diff --git a/azurerm/utils/common_marshal.go b/azurerm/utils/common_marshal.go index f2ee8a633d61..089771ad192c 100644 --- a/azurerm/utils/common_marshal.go +++ b/azurerm/utils/common_marshal.go @@ -20,6 +20,15 @@ func ExpandMapStringPtrString(input map[string]interface{}) map[string]*string { return result } +func ExpandInt32Slice(input []interface{}) *[]int32 { + result := make([]int32, len(input)) + for i, item := range input { + result[i] = int32(item.(int)) + } + + return &result +} + func FlattenStringSlice(input *[]string) []interface{} { result := make([]interface{}, 0) if input != nil { @@ -41,3 +50,13 @@ func FlattenMapStringPtrString(input map[string]*string) map[string]interface{} } return result } + +func FlattenInt32Slice(input *[]int32) []interface{} { + result := make([]interface{}, 0) + if input != nil { + for _, item := range *input { + result = append(result, item) + } + } + return result +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/actionrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/actionrules.go new file mode 100644 index 000000000000..5bfa0ec85a5c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/actionrules.go @@ -0,0 +1,694 @@ +package alertsmanagement + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ActionRulesClient is the alertsManagement Client +type ActionRulesClient struct { + BaseClient +} + +// NewActionRulesClient creates an instance of the ActionRulesClient client. +func NewActionRulesClient(subscriptionID string) ActionRulesClient { + return NewActionRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewActionRulesClientWithBaseURI creates an instance of the ActionRulesClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewActionRulesClientWithBaseURI(baseURI string, subscriptionID string) ActionRulesClient { + return ActionRulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateUpdate creates/Updates a specific action rule +// Parameters: +// resourceGroupName - resource group name where the resource is created. +// actionRuleName - the name of action rule that needs to be created/updated +// actionRule - action rule to be created/updated +func (client ActionRulesClient) CreateUpdate(ctx context.Context, resourceGroupName string, actionRuleName string, actionRule ActionRule) (result ActionRule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.CreateUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.ActionRulesClient", "CreateUpdate", err.Error()) + } + + req, err := client.CreateUpdatePreparer(ctx, resourceGroupName, actionRuleName, actionRule) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "CreateUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "CreateUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "CreateUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateUpdatePreparer prepares the CreateUpdate request. +func (client ActionRulesClient) CreateUpdatePreparer(ctx context.Context, resourceGroupName string, actionRuleName string, actionRule ActionRule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "actionRuleName": autorest.Encode("path", actionRuleName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}", pathParameters), + autorest.WithJSON(actionRule), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateUpdateSender sends the CreateUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ActionRulesClient) CreateUpdateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CreateUpdateResponder handles the response to the CreateUpdate request. The method always +// closes the http.Response Body. +func (client ActionRulesClient) CreateUpdateResponder(resp *http.Response) (result ActionRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a given action rule +// Parameters: +// resourceGroupName - resource group name where the resource is created. +// actionRuleName - the name that needs to be deleted +func (client ActionRulesClient) Delete(ctx context.Context, resourceGroupName string, actionRuleName string) (result Bool, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.Delete") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.ActionRulesClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, actionRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ActionRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, actionRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "actionRuleName": autorest.Encode("path", actionRuleName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ActionRulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ActionRulesClient) DeleteResponder(resp *http.Response) (result Bool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetByName get a specific action rule +// Parameters: +// resourceGroupName - resource group name where the resource is created. +// actionRuleName - the name of action rule that needs to be fetched +func (client ActionRulesClient) GetByName(ctx context.Context, resourceGroupName string, actionRuleName string) (result ActionRule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.GetByName") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.ActionRulesClient", "GetByName", err.Error()) + } + + req, err := client.GetByNamePreparer(ctx, resourceGroupName, actionRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "GetByName", nil, "Failure preparing request") + return + } + + resp, err := client.GetByNameSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "GetByName", resp, "Failure sending request") + return + } + + result, err = client.GetByNameResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "GetByName", resp, "Failure responding to request") + } + + return +} + +// GetByNamePreparer prepares the GetByName request. +func (client ActionRulesClient) GetByNamePreparer(ctx context.Context, resourceGroupName string, actionRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "actionRuleName": autorest.Encode("path", actionRuleName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetByNameSender sends the GetByName request. The method will close the +// http.Response Body if it receives an error. +func (client ActionRulesClient) GetByNameSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetByNameResponder handles the response to the GetByName request. The method always +// closes the http.Response Body. +func (client ActionRulesClient) GetByNameResponder(resp *http.Response) (result ActionRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup list all action rules of the subscription, created in given resource group and given input +// filters +// Parameters: +// resourceGroupName - resource group name where the resource is created. +// targetResourceGroup - filter by target resource group name. Default value is select all. +// targetResourceType - filter by target resource type. Default value is select all. +// targetResource - filter by target resource( which is full ARM ID) Default value is select all. +// severity - filter by severity. Default value is select all. +// monitorService - filter by monitor service which generates the alert instance. Default value is select all. +// impactedScope - filter by impacted/target scope (provide comma separated list for multiple scopes). The +// value should be an well constructed ARM id of the scope. +// description - filter by alert rule description +// alertRuleID - filter by alert rule id +// actionGroup - filter by action group configured as part of action rule +// name - filter by action rule name +func (client ActionRulesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, targetResourceGroup string, targetResourceType string, targetResource string, severity Severity, monitorService MonitorService, impactedScope string, description string, alertRuleID string, actionGroup string, name string) (result ActionRulesListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.arl.Response.Response != nil { + sc = result.arl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.ActionRulesClient", "ListByResourceGroup", err.Error()) + } + + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, targetResourceGroup, targetResourceType, targetResource, severity, monitorService, impactedScope, description, alertRuleID, actionGroup, name) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.arl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.arl, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client ActionRulesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, targetResourceGroup string, targetResourceType string, targetResource string, severity Severity, monitorService MonitorService, impactedScope string, description string, alertRuleID string, actionGroup string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(targetResourceGroup) > 0 { + queryParameters["targetResourceGroup"] = autorest.Encode("query", targetResourceGroup) + } + if len(targetResourceType) > 0 { + queryParameters["targetResourceType"] = autorest.Encode("query", targetResourceType) + } + if len(targetResource) > 0 { + queryParameters["targetResource"] = autorest.Encode("query", targetResource) + } + if len(string(severity)) > 0 { + queryParameters["severity"] = autorest.Encode("query", severity) + } + if len(string(monitorService)) > 0 { + queryParameters["monitorService"] = autorest.Encode("query", monitorService) + } + if len(impactedScope) > 0 { + queryParameters["impactedScope"] = autorest.Encode("query", impactedScope) + } + if len(description) > 0 { + queryParameters["description"] = autorest.Encode("query", description) + } + if len(alertRuleID) > 0 { + queryParameters["alertRuleId"] = autorest.Encode("query", alertRuleID) + } + if len(actionGroup) > 0 { + queryParameters["actionGroup"] = autorest.Encode("query", actionGroup) + } + if len(name) > 0 { + queryParameters["name"] = autorest.Encode("query", name) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ActionRulesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ActionRulesClient) ListByResourceGroupResponder(resp *http.Response) (result ActionRulesList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client ActionRulesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ActionRulesList) (result ActionRulesList, err error) { + req, err := lastResults.actionRulesListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client ActionRulesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, targetResourceGroup string, targetResourceType string, targetResource string, severity Severity, monitorService MonitorService, impactedScope string, description string, alertRuleID string, actionGroup string, name string) (result ActionRulesListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, targetResourceGroup, targetResourceType, targetResource, severity, monitorService, impactedScope, description, alertRuleID, actionGroup, name) + return +} + +// ListBySubscription list all action rules of the subscription and given input filters +// Parameters: +// targetResourceGroup - filter by target resource group name. Default value is select all. +// targetResourceType - filter by target resource type. Default value is select all. +// targetResource - filter by target resource( which is full ARM ID) Default value is select all. +// severity - filter by severity. Default value is select all. +// monitorService - filter by monitor service which generates the alert instance. Default value is select all. +// impactedScope - filter by impacted/target scope (provide comma separated list for multiple scopes). The +// value should be an well constructed ARM id of the scope. +// description - filter by alert rule description +// alertRuleID - filter by alert rule id +// actionGroup - filter by action group configured as part of action rule +// name - filter by action rule name +func (client ActionRulesClient) ListBySubscription(ctx context.Context, targetResourceGroup string, targetResourceType string, targetResource string, severity Severity, monitorService MonitorService, impactedScope string, description string, alertRuleID string, actionGroup string, name string) (result ActionRulesListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.ListBySubscription") + defer func() { + sc := -1 + if result.arl.Response.Response != nil { + sc = result.arl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.ActionRulesClient", "ListBySubscription", err.Error()) + } + + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, targetResourceGroup, targetResourceType, targetResource, severity, monitorService, impactedScope, description, alertRuleID, actionGroup, name) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.arl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.arl, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client ActionRulesClient) ListBySubscriptionPreparer(ctx context.Context, targetResourceGroup string, targetResourceType string, targetResource string, severity Severity, monitorService MonitorService, impactedScope string, description string, alertRuleID string, actionGroup string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(targetResourceGroup) > 0 { + queryParameters["targetResourceGroup"] = autorest.Encode("query", targetResourceGroup) + } + if len(targetResourceType) > 0 { + queryParameters["targetResourceType"] = autorest.Encode("query", targetResourceType) + } + if len(targetResource) > 0 { + queryParameters["targetResource"] = autorest.Encode("query", targetResource) + } + if len(string(severity)) > 0 { + queryParameters["severity"] = autorest.Encode("query", severity) + } + if len(string(monitorService)) > 0 { + queryParameters["monitorService"] = autorest.Encode("query", monitorService) + } + if len(impactedScope) > 0 { + queryParameters["impactedScope"] = autorest.Encode("query", impactedScope) + } + if len(description) > 0 { + queryParameters["description"] = autorest.Encode("query", description) + } + if len(alertRuleID) > 0 { + queryParameters["alertRuleId"] = autorest.Encode("query", alertRuleID) + } + if len(actionGroup) > 0 { + queryParameters["actionGroup"] = autorest.Encode("query", actionGroup) + } + if len(name) > 0 { + queryParameters["name"] = autorest.Encode("query", name) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/actionRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client ActionRulesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client ActionRulesClient) ListBySubscriptionResponder(resp *http.Response) (result ActionRulesList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client ActionRulesClient) listBySubscriptionNextResults(ctx context.Context, lastResults ActionRulesList) (result ActionRulesList, err error) { + req, err := lastResults.actionRulesListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client ActionRulesClient) ListBySubscriptionComplete(ctx context.Context, targetResourceGroup string, targetResourceType string, targetResource string, severity Severity, monitorService MonitorService, impactedScope string, description string, alertRuleID string, actionGroup string, name string) (result ActionRulesListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.ListBySubscription") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBySubscription(ctx, targetResourceGroup, targetResourceType, targetResource, severity, monitorService, impactedScope, description, alertRuleID, actionGroup, name) + return +} + +// Update update enabled flag and/or tags for the given action rule +// Parameters: +// resourceGroupName - resource group name where the resource is created. +// actionRuleName - the name that needs to be updated +// actionRulePatch - parameters supplied to the operation. +func (client ActionRulesClient) Update(ctx context.Context, resourceGroupName string, actionRuleName string, actionRulePatch PatchObject) (result ActionRule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.ActionRulesClient", "Update", err.Error()) + } + + req, err := client.UpdatePreparer(ctx, resourceGroupName, actionRuleName, actionRulePatch) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.ActionRulesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ActionRulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, actionRuleName string, actionRulePatch PatchObject) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "actionRuleName": autorest.Encode("path", actionRuleName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}", pathParameters), + autorest.WithJSON(actionRulePatch), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client ActionRulesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ActionRulesClient) UpdateResponder(resp *http.Response) (result ActionRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/alerts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/alerts.go new file mode 100644 index 000000000000..7e07bb0d037a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/alerts.go @@ -0,0 +1,677 @@ +package alertsmanagement + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// AlertsClient is the alertsManagement Client +type AlertsClient struct { + BaseClient +} + +// NewAlertsClient creates an instance of the AlertsClient client. +func NewAlertsClient(subscriptionID string) AlertsClient { + return NewAlertsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAlertsClientWithBaseURI creates an instance of the AlertsClient client using a custom endpoint. Use this when +// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewAlertsClientWithBaseURI(baseURI string, subscriptionID string) AlertsClient { + return AlertsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ChangeState change the state of an alert. +// Parameters: +// alertID - unique ID of an alert instance. +// newState - new state of the alert. +func (client AlertsClient) ChangeState(ctx context.Context, alertID string, newState AlertState) (result Alert, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.ChangeState") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.AlertsClient", "ChangeState", err.Error()) + } + + req, err := client.ChangeStatePreparer(ctx, alertID, newState) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "ChangeState", nil, "Failure preparing request") + return + } + + resp, err := client.ChangeStateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "ChangeState", resp, "Failure sending request") + return + } + + result, err = client.ChangeStateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "ChangeState", resp, "Failure responding to request") + } + + return +} + +// ChangeStatePreparer prepares the ChangeState request. +func (client AlertsClient) ChangeStatePreparer(ctx context.Context, alertID string, newState AlertState) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alertId": autorest.Encode("path", alertID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + "newState": autorest.Encode("query", newState), + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ChangeStateSender sends the ChangeState request. The method will close the +// http.Response Body if it receives an error. +func (client AlertsClient) ChangeStateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ChangeStateResponder handles the response to the ChangeState request. The method always +// closes the http.Response Body. +func (client AlertsClient) ChangeStateResponder(resp *http.Response) (result Alert, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetAll list all existing alerts, where the results can be filtered on the basis of multiple parameters (e.g. time +// range). The results can then be sorted on the basis specific fields, with the default being lastModifiedDateTime. +// Parameters: +// targetResource - filter by target resource( which is full ARM ID) Default value is select all. +// targetResourceType - filter by target resource type. Default value is select all. +// targetResourceGroup - filter by target resource group name. Default value is select all. +// monitorService - filter by monitor service which generates the alert instance. Default value is select all. +// monitorCondition - filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to +// select all. +// severity - filter by severity. Default value is select all. +// alertState - filter by state of the alert instance. Default value is to select all. +// alertRule - filter by specific alert rule. Default value is to select all. +// smartGroupID - filter the alerts list by the Smart Group Id. Default value is none. +// includeContext - include context which has contextual data specific to the monitor service. Default value is +// false' +// includeEgressConfig - include egress config which would be used for displaying the content in portal. +// Default value is 'false'. +// pageCount - determines number of alerts returned per page in response. Permissible value is between 1 to +// 250. When the "includeContent" filter is selected, maximum value allowed is 25. Default value is 25. +// sortBy - sort the query results by input field, Default value is 'lastModifiedDateTime'. +// sortOrder - sort the query results order in either ascending or descending. Default value is 'desc' for +// time fields and 'asc' for others. +// selectParameter - this filter allows to selection of the fields(comma separated) which would be part of the +// essential section. This would allow to project only the required fields rather than getting entire content. +// Default is to fetch all the fields in the essentials section. +// timeRange - filter by time range by below listed values. Default value is 1 day. +// customTimeRange - filter by custom time range in the format / where time is in +// (ISO-8601 format)'. Permissible values is within 30 days from query time. Either timeRange or +// customTimeRange could be used but not both. Default is none. +func (client AlertsClient) GetAll(ctx context.Context, targetResource string, targetResourceType string, targetResourceGroup string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, alertState AlertState, alertRule string, smartGroupID string, includeContext *bool, includeEgressConfig *bool, pageCount *int32, sortBy AlertsSortByFields, sortOrder string, selectParameter string, timeRange TimeRange, customTimeRange string) (result AlertsListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.GetAll") + defer func() { + sc := -1 + if result.al.Response.Response != nil { + sc = result.al.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.AlertsClient", "GetAll", err.Error()) + } + + result.fn = client.getAllNextResults + req, err := client.GetAllPreparer(ctx, targetResource, targetResourceType, targetResourceGroup, monitorService, monitorCondition, severity, alertState, alertRule, smartGroupID, includeContext, includeEgressConfig, pageCount, sortBy, sortOrder, selectParameter, timeRange, customTimeRange) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetAll", nil, "Failure preparing request") + return + } + + resp, err := client.GetAllSender(req) + if err != nil { + result.al.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetAll", resp, "Failure sending request") + return + } + + result.al, err = client.GetAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetAll", resp, "Failure responding to request") + } + + return +} + +// GetAllPreparer prepares the GetAll request. +func (client AlertsClient) GetAllPreparer(ctx context.Context, targetResource string, targetResourceType string, targetResourceGroup string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, alertState AlertState, alertRule string, smartGroupID string, includeContext *bool, includeEgressConfig *bool, pageCount *int32, sortBy AlertsSortByFields, sortOrder string, selectParameter string, timeRange TimeRange, customTimeRange string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(targetResource) > 0 { + queryParameters["targetResource"] = autorest.Encode("query", targetResource) + } + if len(targetResourceType) > 0 { + queryParameters["targetResourceType"] = autorest.Encode("query", targetResourceType) + } + if len(targetResourceGroup) > 0 { + queryParameters["targetResourceGroup"] = autorest.Encode("query", targetResourceGroup) + } + if len(string(monitorService)) > 0 { + queryParameters["monitorService"] = autorest.Encode("query", monitorService) + } + if len(string(monitorCondition)) > 0 { + queryParameters["monitorCondition"] = autorest.Encode("query", monitorCondition) + } + if len(string(severity)) > 0 { + queryParameters["severity"] = autorest.Encode("query", severity) + } + if len(string(alertState)) > 0 { + queryParameters["alertState"] = autorest.Encode("query", alertState) + } + if len(alertRule) > 0 { + queryParameters["alertRule"] = autorest.Encode("query", alertRule) + } + if len(smartGroupID) > 0 { + queryParameters["smartGroupId"] = autorest.Encode("query", smartGroupID) + } + if includeContext != nil { + queryParameters["includeContext"] = autorest.Encode("query", *includeContext) + } + if includeEgressConfig != nil { + queryParameters["includeEgressConfig"] = autorest.Encode("query", *includeEgressConfig) + } + if pageCount != nil { + queryParameters["pageCount"] = autorest.Encode("query", *pageCount) + } + if len(string(sortBy)) > 0 { + queryParameters["sortBy"] = autorest.Encode("query", sortBy) + } + if len(string(sortOrder)) > 0 { + queryParameters["sortOrder"] = autorest.Encode("query", sortOrder) + } + if len(selectParameter) > 0 { + queryParameters["select"] = autorest.Encode("query", selectParameter) + } + if len(string(timeRange)) > 0 { + queryParameters["timeRange"] = autorest.Encode("query", timeRange) + } + if len(customTimeRange) > 0 { + queryParameters["customTimeRange"] = autorest.Encode("query", customTimeRange) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetAllSender sends the GetAll request. The method will close the +// http.Response Body if it receives an error. +func (client AlertsClient) GetAllSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetAllResponder handles the response to the GetAll request. The method always +// closes the http.Response Body. +func (client AlertsClient) GetAllResponder(resp *http.Response) (result AlertsList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// getAllNextResults retrieves the next set of results, if any. +func (client AlertsClient) getAllNextResults(ctx context.Context, lastResults AlertsList) (result AlertsList, err error) { + req, err := lastResults.alertsListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "getAllNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.GetAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "getAllNextResults", resp, "Failure sending next results request") + } + result, err = client.GetAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "getAllNextResults", resp, "Failure responding to next results request") + } + return +} + +// GetAllComplete enumerates all values, automatically crossing page boundaries as required. +func (client AlertsClient) GetAllComplete(ctx context.Context, targetResource string, targetResourceType string, targetResourceGroup string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, alertState AlertState, alertRule string, smartGroupID string, includeContext *bool, includeEgressConfig *bool, pageCount *int32, sortBy AlertsSortByFields, sortOrder string, selectParameter string, timeRange TimeRange, customTimeRange string) (result AlertsListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.GetAll") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.GetAll(ctx, targetResource, targetResourceType, targetResourceGroup, monitorService, monitorCondition, severity, alertState, alertRule, smartGroupID, includeContext, includeEgressConfig, pageCount, sortBy, sortOrder, selectParameter, timeRange, customTimeRange) + return +} + +// GetByID get information related to a specific alert +// Parameters: +// alertID - unique ID of an alert instance. +func (client AlertsClient) GetByID(ctx context.Context, alertID string) (result Alert, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.GetByID") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.AlertsClient", "GetByID", err.Error()) + } + + req, err := client.GetByIDPreparer(ctx, alertID) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetByID", nil, "Failure preparing request") + return + } + + resp, err := client.GetByIDSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetByID", resp, "Failure sending request") + return + } + + result, err = client.GetByIDResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetByID", resp, "Failure responding to request") + } + + return +} + +// GetByIDPreparer prepares the GetByID request. +func (client AlertsClient) GetByIDPreparer(ctx context.Context, alertID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alertId": autorest.Encode("path", alertID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetByIDSender sends the GetByID request. The method will close the +// http.Response Body if it receives an error. +func (client AlertsClient) GetByIDSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetByIDResponder handles the response to the GetByID request. The method always +// closes the http.Response Body. +func (client AlertsClient) GetByIDResponder(resp *http.Response) (result Alert, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetHistory get the history of an alert, which captures any monitor condition changes (Fired/Resolved) and alert +// state changes (New/Acknowledged/Closed). +// Parameters: +// alertID - unique ID of an alert instance. +func (client AlertsClient) GetHistory(ctx context.Context, alertID string) (result AlertModification, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.GetHistory") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.AlertsClient", "GetHistory", err.Error()) + } + + req, err := client.GetHistoryPreparer(ctx, alertID) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetHistory", nil, "Failure preparing request") + return + } + + resp, err := client.GetHistorySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetHistory", resp, "Failure sending request") + return + } + + result, err = client.GetHistoryResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetHistory", resp, "Failure responding to request") + } + + return +} + +// GetHistoryPreparer prepares the GetHistory request. +func (client AlertsClient) GetHistoryPreparer(ctx context.Context, alertID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alertId": autorest.Encode("path", alertID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetHistorySender sends the GetHistory request. The method will close the +// http.Response Body if it receives an error. +func (client AlertsClient) GetHistorySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetHistoryResponder handles the response to the GetHistory request. The method always +// closes the http.Response Body. +func (client AlertsClient) GetHistoryResponder(resp *http.Response) (result AlertModification, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetSummary get a summarized count of your alerts grouped by various parameters (e.g. grouping by 'Severity' returns +// the count of alerts for each severity). +// Parameters: +// groupby - this parameter allows the result set to be grouped by input fields (Maximum 2 comma separated +// fields supported). For example, groupby=severity or groupby=severity,alertstate. +// includeSmartGroupsCount - include count of the SmartGroups as part of the summary. Default value is 'false'. +// targetResource - filter by target resource( which is full ARM ID) Default value is select all. +// targetResourceType - filter by target resource type. Default value is select all. +// targetResourceGroup - filter by target resource group name. Default value is select all. +// monitorService - filter by monitor service which generates the alert instance. Default value is select all. +// monitorCondition - filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to +// select all. +// severity - filter by severity. Default value is select all. +// alertState - filter by state of the alert instance. Default value is to select all. +// alertRule - filter by specific alert rule. Default value is to select all. +// timeRange - filter by time range by below listed values. Default value is 1 day. +// customTimeRange - filter by custom time range in the format / where time is in +// (ISO-8601 format)'. Permissible values is within 30 days from query time. Either timeRange or +// customTimeRange could be used but not both. Default is none. +func (client AlertsClient) GetSummary(ctx context.Context, groupby AlertsSummaryGroupByFields, includeSmartGroupsCount *bool, targetResource string, targetResourceType string, targetResourceGroup string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, alertState AlertState, alertRule string, timeRange TimeRange, customTimeRange string) (result AlertsSummary, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.GetSummary") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.AlertsClient", "GetSummary", err.Error()) + } + + req, err := client.GetSummaryPreparer(ctx, groupby, includeSmartGroupsCount, targetResource, targetResourceType, targetResourceGroup, monitorService, monitorCondition, severity, alertState, alertRule, timeRange, customTimeRange) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetSummary", nil, "Failure preparing request") + return + } + + resp, err := client.GetSummarySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetSummary", resp, "Failure sending request") + return + } + + result, err = client.GetSummaryResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "GetSummary", resp, "Failure responding to request") + } + + return +} + +// GetSummaryPreparer prepares the GetSummary request. +func (client AlertsClient) GetSummaryPreparer(ctx context.Context, groupby AlertsSummaryGroupByFields, includeSmartGroupsCount *bool, targetResource string, targetResourceType string, targetResourceGroup string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, alertState AlertState, alertRule string, timeRange TimeRange, customTimeRange string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + "groupby": autorest.Encode("query", groupby), + } + if includeSmartGroupsCount != nil { + queryParameters["includeSmartGroupsCount"] = autorest.Encode("query", *includeSmartGroupsCount) + } + if len(targetResource) > 0 { + queryParameters["targetResource"] = autorest.Encode("query", targetResource) + } + if len(targetResourceType) > 0 { + queryParameters["targetResourceType"] = autorest.Encode("query", targetResourceType) + } + if len(targetResourceGroup) > 0 { + queryParameters["targetResourceGroup"] = autorest.Encode("query", targetResourceGroup) + } + if len(string(monitorService)) > 0 { + queryParameters["monitorService"] = autorest.Encode("query", monitorService) + } + if len(string(monitorCondition)) > 0 { + queryParameters["monitorCondition"] = autorest.Encode("query", monitorCondition) + } + if len(string(severity)) > 0 { + queryParameters["severity"] = autorest.Encode("query", severity) + } + if len(string(alertState)) > 0 { + queryParameters["alertState"] = autorest.Encode("query", alertState) + } + if len(alertRule) > 0 { + queryParameters["alertRule"] = autorest.Encode("query", alertRule) + } + if len(string(timeRange)) > 0 { + queryParameters["timeRange"] = autorest.Encode("query", timeRange) + } + if len(customTimeRange) > 0 { + queryParameters["customTimeRange"] = autorest.Encode("query", customTimeRange) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertsSummary", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSummarySender sends the GetSummary request. The method will close the +// http.Response Body if it receives an error. +func (client AlertsClient) GetSummarySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetSummaryResponder handles the response to the GetSummary request. The method always +// closes the http.Response Body. +func (client AlertsClient) GetSummaryResponder(resp *http.Response) (result AlertsSummary, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// MetaData list alerts meta data information based on value of identifier parameter. +func (client AlertsClient) MetaData(ctx context.Context) (result AlertsMetaData, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsClient.MetaData") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.MetaDataPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "MetaData", nil, "Failure preparing request") + return + } + + resp, err := client.MetaDataSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "MetaData", resp, "Failure sending request") + return + } + + result, err = client.MetaDataResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.AlertsClient", "MetaData", resp, "Failure responding to request") + } + + return +} + +// MetaDataPreparer prepares the MetaData request. +func (client AlertsClient) MetaDataPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + "identifier": autorest.Encode("query", "MonitorServiceList"), + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.AlertsManagement/alertsMetaData"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// MetaDataSender sends the MetaData request. The method will close the +// http.Response Body if it receives an error. +func (client AlertsClient) MetaDataSender(req *http.Request) (*http.Response, error) { + return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// MetaDataResponder handles the response to the MetaData request. The method always +// closes the http.Response Body. +func (client AlertsClient) MetaDataResponder(resp *http.Response) (result AlertsMetaData, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/client.go new file mode 100644 index 000000000000..b0ed5bbf650b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/client.go @@ -0,0 +1,52 @@ +// Package alertsmanagement implements the Azure ARM Alertsmanagement service API version 2019-05-05-preview. +// +// AlertsManagement Client +package alertsmanagement + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Alertsmanagement + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Alertsmanagement. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with +// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/models.go new file mode 100644 index 000000000000..cb42cbdb47fa --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/models.go @@ -0,0 +1,2038 @@ +package alertsmanagement + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement" + +// ActionRuleStatus enumerates the values for action rule status. +type ActionRuleStatus string + +const ( + // Disabled ... + Disabled ActionRuleStatus = "Disabled" + // Enabled ... + Enabled ActionRuleStatus = "Enabled" +) + +// PossibleActionRuleStatusValues returns an array of possible values for the ActionRuleStatus const type. +func PossibleActionRuleStatusValues() []ActionRuleStatus { + return []ActionRuleStatus{Disabled, Enabled} +} + +// AlertModificationEvent enumerates the values for alert modification event. +type AlertModificationEvent string + +const ( + // AlertCreated ... + AlertCreated AlertModificationEvent = "AlertCreated" + // MonitorConditionChange ... + MonitorConditionChange AlertModificationEvent = "MonitorConditionChange" + // StateChange ... + StateChange AlertModificationEvent = "StateChange" +) + +// PossibleAlertModificationEventValues returns an array of possible values for the AlertModificationEvent const type. +func PossibleAlertModificationEventValues() []AlertModificationEvent { + return []AlertModificationEvent{AlertCreated, MonitorConditionChange, StateChange} +} + +// AlertsSortByFields enumerates the values for alerts sort by fields. +type AlertsSortByFields string + +const ( + // AlertsSortByFieldsAlertState ... + AlertsSortByFieldsAlertState AlertsSortByFields = "alertState" + // AlertsSortByFieldsLastModifiedDateTime ... + AlertsSortByFieldsLastModifiedDateTime AlertsSortByFields = "lastModifiedDateTime" + // AlertsSortByFieldsMonitorCondition ... + AlertsSortByFieldsMonitorCondition AlertsSortByFields = "monitorCondition" + // AlertsSortByFieldsName ... + AlertsSortByFieldsName AlertsSortByFields = "name" + // AlertsSortByFieldsSeverity ... + AlertsSortByFieldsSeverity AlertsSortByFields = "severity" + // AlertsSortByFieldsStartDateTime ... + AlertsSortByFieldsStartDateTime AlertsSortByFields = "startDateTime" + // AlertsSortByFieldsTargetResource ... + AlertsSortByFieldsTargetResource AlertsSortByFields = "targetResource" + // AlertsSortByFieldsTargetResourceGroup ... + AlertsSortByFieldsTargetResourceGroup AlertsSortByFields = "targetResourceGroup" + // AlertsSortByFieldsTargetResourceName ... + AlertsSortByFieldsTargetResourceName AlertsSortByFields = "targetResourceName" + // AlertsSortByFieldsTargetResourceType ... + AlertsSortByFieldsTargetResourceType AlertsSortByFields = "targetResourceType" +) + +// PossibleAlertsSortByFieldsValues returns an array of possible values for the AlertsSortByFields const type. +func PossibleAlertsSortByFieldsValues() []AlertsSortByFields { + return []AlertsSortByFields{AlertsSortByFieldsAlertState, AlertsSortByFieldsLastModifiedDateTime, AlertsSortByFieldsMonitorCondition, AlertsSortByFieldsName, AlertsSortByFieldsSeverity, AlertsSortByFieldsStartDateTime, AlertsSortByFieldsTargetResource, AlertsSortByFieldsTargetResourceGroup, AlertsSortByFieldsTargetResourceName, AlertsSortByFieldsTargetResourceType} +} + +// AlertsSummaryGroupByFields enumerates the values for alerts summary group by fields. +type AlertsSummaryGroupByFields string + +const ( + // AlertsSummaryGroupByFieldsAlertRule ... + AlertsSummaryGroupByFieldsAlertRule AlertsSummaryGroupByFields = "alertRule" + // AlertsSummaryGroupByFieldsAlertState ... + AlertsSummaryGroupByFieldsAlertState AlertsSummaryGroupByFields = "alertState" + // AlertsSummaryGroupByFieldsMonitorCondition ... + AlertsSummaryGroupByFieldsMonitorCondition AlertsSummaryGroupByFields = "monitorCondition" + // AlertsSummaryGroupByFieldsMonitorService ... + AlertsSummaryGroupByFieldsMonitorService AlertsSummaryGroupByFields = "monitorService" + // AlertsSummaryGroupByFieldsSeverity ... + AlertsSummaryGroupByFieldsSeverity AlertsSummaryGroupByFields = "severity" + // AlertsSummaryGroupByFieldsSignalType ... + AlertsSummaryGroupByFieldsSignalType AlertsSummaryGroupByFields = "signalType" +) + +// PossibleAlertsSummaryGroupByFieldsValues returns an array of possible values for the AlertsSummaryGroupByFields const type. +func PossibleAlertsSummaryGroupByFieldsValues() []AlertsSummaryGroupByFields { + return []AlertsSummaryGroupByFields{AlertsSummaryGroupByFieldsAlertRule, AlertsSummaryGroupByFieldsAlertState, AlertsSummaryGroupByFieldsMonitorCondition, AlertsSummaryGroupByFieldsMonitorService, AlertsSummaryGroupByFieldsSeverity, AlertsSummaryGroupByFieldsSignalType} +} + +// AlertState enumerates the values for alert state. +type AlertState string + +const ( + // AlertStateAcknowledged ... + AlertStateAcknowledged AlertState = "Acknowledged" + // AlertStateClosed ... + AlertStateClosed AlertState = "Closed" + // AlertStateNew ... + AlertStateNew AlertState = "New" +) + +// PossibleAlertStateValues returns an array of possible values for the AlertState const type. +func PossibleAlertStateValues() []AlertState { + return []AlertState{AlertStateAcknowledged, AlertStateClosed, AlertStateNew} +} + +// MetadataIdentifier enumerates the values for metadata identifier. +type MetadataIdentifier string + +const ( + // MetadataIdentifierAlertsMetaDataProperties ... + MetadataIdentifierAlertsMetaDataProperties MetadataIdentifier = "alertsMetaDataProperties" + // MetadataIdentifierMonitorServiceList ... + MetadataIdentifierMonitorServiceList MetadataIdentifier = "MonitorServiceList" +) + +// PossibleMetadataIdentifierValues returns an array of possible values for the MetadataIdentifier const type. +func PossibleMetadataIdentifierValues() []MetadataIdentifier { + return []MetadataIdentifier{MetadataIdentifierAlertsMetaDataProperties, MetadataIdentifierMonitorServiceList} +} + +// MonitorCondition enumerates the values for monitor condition. +type MonitorCondition string + +const ( + // Fired ... + Fired MonitorCondition = "Fired" + // Resolved ... + Resolved MonitorCondition = "Resolved" +) + +// PossibleMonitorConditionValues returns an array of possible values for the MonitorCondition const type. +func PossibleMonitorConditionValues() []MonitorCondition { + return []MonitorCondition{Fired, Resolved} +} + +// MonitorService enumerates the values for monitor service. +type MonitorService string + +const ( + // ActivityLogAdministrative ... + ActivityLogAdministrative MonitorService = "ActivityLog Administrative" + // ActivityLogAutoscale ... + ActivityLogAutoscale MonitorService = "ActivityLog Autoscale" + // ActivityLogPolicy ... + ActivityLogPolicy MonitorService = "ActivityLog Policy" + // ActivityLogRecommendation ... + ActivityLogRecommendation MonitorService = "ActivityLog Recommendation" + // ActivityLogSecurity ... + ActivityLogSecurity MonitorService = "ActivityLog Security" + // ApplicationInsights ... + ApplicationInsights MonitorService = "Application Insights" + // LogAnalytics ... + LogAnalytics MonitorService = "Log Analytics" + // Nagios ... + Nagios MonitorService = "Nagios" + // Platform ... + Platform MonitorService = "Platform" + // SCOM ... + SCOM MonitorService = "SCOM" + // ServiceHealth ... + ServiceHealth MonitorService = "ServiceHealth" + // SmartDetector ... + SmartDetector MonitorService = "SmartDetector" + // VMInsights ... + VMInsights MonitorService = "VM Insights" + // Zabbix ... + Zabbix MonitorService = "Zabbix" +) + +// PossibleMonitorServiceValues returns an array of possible values for the MonitorService const type. +func PossibleMonitorServiceValues() []MonitorService { + return []MonitorService{ActivityLogAdministrative, ActivityLogAutoscale, ActivityLogPolicy, ActivityLogRecommendation, ActivityLogSecurity, ApplicationInsights, LogAnalytics, Nagios, Platform, SCOM, ServiceHealth, SmartDetector, VMInsights, Zabbix} +} + +// Operator enumerates the values for operator. +type Operator string + +const ( + // Contains ... + Contains Operator = "Contains" + // DoesNotContain ... + DoesNotContain Operator = "DoesNotContain" + // Equals ... + Equals Operator = "Equals" + // NotEquals ... + NotEquals Operator = "NotEquals" +) + +// PossibleOperatorValues returns an array of possible values for the Operator const type. +func PossibleOperatorValues() []Operator { + return []Operator{Contains, DoesNotContain, Equals, NotEquals} +} + +// ScopeType enumerates the values for scope type. +type ScopeType string + +const ( + // ScopeTypeResource ... + ScopeTypeResource ScopeType = "Resource" + // ScopeTypeResourceGroup ... + ScopeTypeResourceGroup ScopeType = "ResourceGroup" +) + +// PossibleScopeTypeValues returns an array of possible values for the ScopeType const type. +func PossibleScopeTypeValues() []ScopeType { + return []ScopeType{ScopeTypeResource, ScopeTypeResourceGroup} +} + +// Severity enumerates the values for severity. +type Severity string + +const ( + // Sev0 ... + Sev0 Severity = "Sev0" + // Sev1 ... + Sev1 Severity = "Sev1" + // Sev2 ... + Sev2 Severity = "Sev2" + // Sev3 ... + Sev3 Severity = "Sev3" + // Sev4 ... + Sev4 Severity = "Sev4" +) + +// PossibleSeverityValues returns an array of possible values for the Severity const type. +func PossibleSeverityValues() []Severity { + return []Severity{Sev0, Sev1, Sev2, Sev3, Sev4} +} + +// SignalType enumerates the values for signal type. +type SignalType string + +const ( + // Log ... + Log SignalType = "Log" + // Metric ... + Metric SignalType = "Metric" + // Unknown ... + Unknown SignalType = "Unknown" +) + +// PossibleSignalTypeValues returns an array of possible values for the SignalType const type. +func PossibleSignalTypeValues() []SignalType { + return []SignalType{Log, Metric, Unknown} +} + +// SmartGroupModificationEvent enumerates the values for smart group modification event. +type SmartGroupModificationEvent string + +const ( + // SmartGroupModificationEventAlertAdded ... + SmartGroupModificationEventAlertAdded SmartGroupModificationEvent = "AlertAdded" + // SmartGroupModificationEventAlertRemoved ... + SmartGroupModificationEventAlertRemoved SmartGroupModificationEvent = "AlertRemoved" + // SmartGroupModificationEventSmartGroupCreated ... + SmartGroupModificationEventSmartGroupCreated SmartGroupModificationEvent = "SmartGroupCreated" + // SmartGroupModificationEventStateChange ... + SmartGroupModificationEventStateChange SmartGroupModificationEvent = "StateChange" +) + +// PossibleSmartGroupModificationEventValues returns an array of possible values for the SmartGroupModificationEvent const type. +func PossibleSmartGroupModificationEventValues() []SmartGroupModificationEvent { + return []SmartGroupModificationEvent{SmartGroupModificationEventAlertAdded, SmartGroupModificationEventAlertRemoved, SmartGroupModificationEventSmartGroupCreated, SmartGroupModificationEventStateChange} +} + +// SmartGroupsSortByFields enumerates the values for smart groups sort by fields. +type SmartGroupsSortByFields string + +const ( + // SmartGroupsSortByFieldsAlertsCount ... + SmartGroupsSortByFieldsAlertsCount SmartGroupsSortByFields = "alertsCount" + // SmartGroupsSortByFieldsLastModifiedDateTime ... + SmartGroupsSortByFieldsLastModifiedDateTime SmartGroupsSortByFields = "lastModifiedDateTime" + // SmartGroupsSortByFieldsSeverity ... + SmartGroupsSortByFieldsSeverity SmartGroupsSortByFields = "severity" + // SmartGroupsSortByFieldsStartDateTime ... + SmartGroupsSortByFieldsStartDateTime SmartGroupsSortByFields = "startDateTime" + // SmartGroupsSortByFieldsState ... + SmartGroupsSortByFieldsState SmartGroupsSortByFields = "state" +) + +// PossibleSmartGroupsSortByFieldsValues returns an array of possible values for the SmartGroupsSortByFields const type. +func PossibleSmartGroupsSortByFieldsValues() []SmartGroupsSortByFields { + return []SmartGroupsSortByFields{SmartGroupsSortByFieldsAlertsCount, SmartGroupsSortByFieldsLastModifiedDateTime, SmartGroupsSortByFieldsSeverity, SmartGroupsSortByFieldsStartDateTime, SmartGroupsSortByFieldsState} +} + +// State enumerates the values for state. +type State string + +const ( + // StateAcknowledged ... + StateAcknowledged State = "Acknowledged" + // StateClosed ... + StateClosed State = "Closed" + // StateNew ... + StateNew State = "New" +) + +// PossibleStateValues returns an array of possible values for the State const type. +func PossibleStateValues() []State { + return []State{StateAcknowledged, StateClosed, StateNew} +} + +// SuppressionType enumerates the values for suppression type. +type SuppressionType string + +const ( + // Always ... + Always SuppressionType = "Always" + // Daily ... + Daily SuppressionType = "Daily" + // Monthly ... + Monthly SuppressionType = "Monthly" + // Once ... + Once SuppressionType = "Once" + // Weekly ... + Weekly SuppressionType = "Weekly" +) + +// PossibleSuppressionTypeValues returns an array of possible values for the SuppressionType const type. +func PossibleSuppressionTypeValues() []SuppressionType { + return []SuppressionType{Always, Daily, Monthly, Once, Weekly} +} + +// TimeRange enumerates the values for time range. +type TimeRange string + +const ( + // Oned ... + Oned TimeRange = "1d" + // Oneh ... + Oneh TimeRange = "1h" + // Sevend ... + Sevend TimeRange = "7d" + // ThreeZerod ... + ThreeZerod TimeRange = "30d" +) + +// PossibleTimeRangeValues returns an array of possible values for the TimeRange const type. +func PossibleTimeRangeValues() []TimeRange { + return []TimeRange{Oned, Oneh, Sevend, ThreeZerod} +} + +// Type enumerates the values for type. +type Type string + +const ( + // TypeActionGroup ... + TypeActionGroup Type = "ActionGroup" + // TypeActionRuleProperties ... + TypeActionRuleProperties Type = "ActionRuleProperties" + // TypeDiagnostics ... + TypeDiagnostics Type = "Diagnostics" + // TypeSuppression ... + TypeSuppression Type = "Suppression" +) + +// PossibleTypeValues returns an array of possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{TypeActionGroup, TypeActionRuleProperties, TypeDiagnostics, TypeSuppression} +} + +// ActionGroup action rule with action group configuration +type ActionGroup struct { + // ActionGroupID - Action group to trigger if action rule matches + ActionGroupID *string `json:"actionGroupId,omitempty"` + // Scope - scope on which action rule will apply + Scope *Scope `json:"scope,omitempty"` + // Conditions - conditions on which alerts will be filtered + Conditions *Conditions `json:"conditions,omitempty"` + // Description - Description of action rule + Description *string `json:"description,omitempty"` + // CreatedAt - READ-ONLY; Creation time of action rule. Date-Time in ISO-8601 format. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // LastModifiedAt - READ-ONLY; Last updated time of action rule. Date-Time in ISO-8601 format. + LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` + // CreatedBy - READ-ONLY; Created by user name. + CreatedBy *string `json:"createdBy,omitempty"` + // LastModifiedBy - READ-ONLY; Last modified by user name. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + // Status - Indicates if the given action rule is enabled or disabled. Possible values include: 'Enabled', 'Disabled' + Status ActionRuleStatus `json:"status,omitempty"` + // Type - Possible values include: 'TypeActionRuleProperties', 'TypeSuppression', 'TypeActionGroup', 'TypeDiagnostics' + Type Type `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ActionGroup. +func (ag ActionGroup) MarshalJSON() ([]byte, error) { + ag.Type = TypeActionGroup + objectMap := make(map[string]interface{}) + if ag.ActionGroupID != nil { + objectMap["actionGroupId"] = ag.ActionGroupID + } + if ag.Scope != nil { + objectMap["scope"] = ag.Scope + } + if ag.Conditions != nil { + objectMap["conditions"] = ag.Conditions + } + if ag.Description != nil { + objectMap["description"] = ag.Description + } + if ag.Status != "" { + objectMap["status"] = ag.Status + } + if ag.Type != "" { + objectMap["type"] = ag.Type + } + return json.Marshal(objectMap) +} + +// AsSuppression is the BasicActionRuleProperties implementation for ActionGroup. +func (ag ActionGroup) AsSuppression() (*Suppression, bool) { + return nil, false +} + +// AsActionGroup is the BasicActionRuleProperties implementation for ActionGroup. +func (ag ActionGroup) AsActionGroup() (*ActionGroup, bool) { + return &ag, true +} + +// AsDiagnostics is the BasicActionRuleProperties implementation for ActionGroup. +func (ag ActionGroup) AsDiagnostics() (*Diagnostics, bool) { + return nil, false +} + +// AsActionRuleProperties is the BasicActionRuleProperties implementation for ActionGroup. +func (ag ActionGroup) AsActionRuleProperties() (*ActionRuleProperties, bool) { + return nil, false +} + +// AsBasicActionRuleProperties is the BasicActionRuleProperties implementation for ActionGroup. +func (ag ActionGroup) AsBasicActionRuleProperties() (BasicActionRuleProperties, bool) { + return &ag, true +} + +// ActionRule action rule object containing target scope, conditions and suppression logic +type ActionRule struct { + autorest.Response `json:"-"` + // Properties - action rule properties + Properties BasicActionRuleProperties `json:"properties,omitempty"` + // Location - Resource location + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// MarshalJSON is the custom marshaler for ActionRule. +func (ar ActionRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + objectMap["properties"] = ar.Properties + if ar.Location != nil { + objectMap["location"] = ar.Location + } + if ar.Tags != nil { + objectMap["tags"] = ar.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ActionRule struct. +func (ar *ActionRule) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + properties, err := unmarshalBasicActionRuleProperties(*v) + if err != nil { + return err + } + ar.Properties = properties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + ar.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + ar.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ar.ID = &ID + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ar.Type = &typeVar + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ar.Name = &name + } + } + } + + return nil +} + +// BasicActionRuleProperties action rule properties defining scope, conditions, suppression logic for action rule +type BasicActionRuleProperties interface { + AsSuppression() (*Suppression, bool) + AsActionGroup() (*ActionGroup, bool) + AsDiagnostics() (*Diagnostics, bool) + AsActionRuleProperties() (*ActionRuleProperties, bool) +} + +// ActionRuleProperties action rule properties defining scope, conditions, suppression logic for action rule +type ActionRuleProperties struct { + // Scope - scope on which action rule will apply + Scope *Scope `json:"scope,omitempty"` + // Conditions - conditions on which alerts will be filtered + Conditions *Conditions `json:"conditions,omitempty"` + // Description - Description of action rule + Description *string `json:"description,omitempty"` + // CreatedAt - READ-ONLY; Creation time of action rule. Date-Time in ISO-8601 format. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // LastModifiedAt - READ-ONLY; Last updated time of action rule. Date-Time in ISO-8601 format. + LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` + // CreatedBy - READ-ONLY; Created by user name. + CreatedBy *string `json:"createdBy,omitempty"` + // LastModifiedBy - READ-ONLY; Last modified by user name. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + // Status - Indicates if the given action rule is enabled or disabled. Possible values include: 'Enabled', 'Disabled' + Status ActionRuleStatus `json:"status,omitempty"` + // Type - Possible values include: 'TypeActionRuleProperties', 'TypeSuppression', 'TypeActionGroup', 'TypeDiagnostics' + Type Type `json:"type,omitempty"` +} + +func unmarshalBasicActionRuleProperties(body []byte) (BasicActionRuleProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["type"] { + case string(TypeSuppression): + var s Suppression + err := json.Unmarshal(body, &s) + return s, err + case string(TypeActionGroup): + var ag ActionGroup + err := json.Unmarshal(body, &ag) + return ag, err + case string(TypeDiagnostics): + var d Diagnostics + err := json.Unmarshal(body, &d) + return d, err + default: + var arp ActionRuleProperties + err := json.Unmarshal(body, &arp) + return arp, err + } +} +func unmarshalBasicActionRulePropertiesArray(body []byte) ([]BasicActionRuleProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + arpArray := make([]BasicActionRuleProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + arp, err := unmarshalBasicActionRuleProperties(*rawMessage) + if err != nil { + return nil, err + } + arpArray[index] = arp + } + return arpArray, nil +} + +// MarshalJSON is the custom marshaler for ActionRuleProperties. +func (arp ActionRuleProperties) MarshalJSON() ([]byte, error) { + arp.Type = TypeActionRuleProperties + objectMap := make(map[string]interface{}) + if arp.Scope != nil { + objectMap["scope"] = arp.Scope + } + if arp.Conditions != nil { + objectMap["conditions"] = arp.Conditions + } + if arp.Description != nil { + objectMap["description"] = arp.Description + } + if arp.Status != "" { + objectMap["status"] = arp.Status + } + if arp.Type != "" { + objectMap["type"] = arp.Type + } + return json.Marshal(objectMap) +} + +// AsSuppression is the BasicActionRuleProperties implementation for ActionRuleProperties. +func (arp ActionRuleProperties) AsSuppression() (*Suppression, bool) { + return nil, false +} + +// AsActionGroup is the BasicActionRuleProperties implementation for ActionRuleProperties. +func (arp ActionRuleProperties) AsActionGroup() (*ActionGroup, bool) { + return nil, false +} + +// AsDiagnostics is the BasicActionRuleProperties implementation for ActionRuleProperties. +func (arp ActionRuleProperties) AsDiagnostics() (*Diagnostics, bool) { + return nil, false +} + +// AsActionRuleProperties is the BasicActionRuleProperties implementation for ActionRuleProperties. +func (arp ActionRuleProperties) AsActionRuleProperties() (*ActionRuleProperties, bool) { + return &arp, true +} + +// AsBasicActionRuleProperties is the BasicActionRuleProperties implementation for ActionRuleProperties. +func (arp ActionRuleProperties) AsBasicActionRuleProperties() (BasicActionRuleProperties, bool) { + return &arp, true +} + +// ActionRulesList list of action rules +type ActionRulesList struct { + autorest.Response `json:"-"` + // NextLink - URL to fetch the next set of action rules + NextLink *string `json:"nextLink,omitempty"` + // Value - List of action rules + Value *[]ActionRule `json:"value,omitempty"` +} + +// ActionRulesListIterator provides access to a complete listing of ActionRule values. +type ActionRulesListIterator struct { + i int + page ActionRulesListPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ActionRulesListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ActionRulesListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ActionRulesListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ActionRulesListIterator) Response() ActionRulesList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ActionRulesListIterator) Value() ActionRule { + if !iter.page.NotDone() { + return ActionRule{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ActionRulesListIterator type. +func NewActionRulesListIterator(page ActionRulesListPage) ActionRulesListIterator { + return ActionRulesListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (arl ActionRulesList) IsEmpty() bool { + return arl.Value == nil || len(*arl.Value) == 0 +} + +// actionRulesListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (arl ActionRulesList) actionRulesListPreparer(ctx context.Context) (*http.Request, error) { + if arl.NextLink == nil || len(to.String(arl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(arl.NextLink))) +} + +// ActionRulesListPage contains a page of ActionRule values. +type ActionRulesListPage struct { + fn func(context.Context, ActionRulesList) (ActionRulesList, error) + arl ActionRulesList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ActionRulesListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ActionRulesListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.arl) + if err != nil { + return err + } + page.arl = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ActionRulesListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ActionRulesListPage) NotDone() bool { + return !page.arl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ActionRulesListPage) Response() ActionRulesList { + return page.arl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ActionRulesListPage) Values() []ActionRule { + if page.arl.IsEmpty() { + return nil + } + return *page.arl.Value +} + +// Creates a new instance of the ActionRulesListPage type. +func NewActionRulesListPage(getNextPage func(context.Context, ActionRulesList) (ActionRulesList, error)) ActionRulesListPage { + return ActionRulesListPage{fn: getNextPage} +} + +// Alert an alert created in alert management service. +type Alert struct { + autorest.Response `json:"-"` + Properties *AlertProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// AlertModification alert Modification details +type AlertModification struct { + autorest.Response `json:"-"` + Properties *AlertModificationProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// AlertModificationItem alert modification item. +type AlertModificationItem struct { + // ModificationEvent - Reason for the modification. Possible values include: 'AlertCreated', 'StateChange', 'MonitorConditionChange' + ModificationEvent AlertModificationEvent `json:"modificationEvent,omitempty"` + // OldValue - Old value + OldValue *string `json:"oldValue,omitempty"` + // NewValue - New value + NewValue *string `json:"newValue,omitempty"` + // ModifiedAt - Modified date and time + ModifiedAt *string `json:"modifiedAt,omitempty"` + // ModifiedBy - Modified user details (Principal client name) + ModifiedBy *string `json:"modifiedBy,omitempty"` + // Comments - Modification comments + Comments *string `json:"comments,omitempty"` + // Description - Description of the modification + Description *string `json:"description,omitempty"` +} + +// AlertModificationProperties properties of the alert modification item. +type AlertModificationProperties struct { + // AlertID - READ-ONLY; Unique Id of the alert for which the history is being retrieved + AlertID *string `json:"alertId,omitempty"` + // Modifications - Modification details + Modifications *[]AlertModificationItem `json:"modifications,omitempty"` +} + +// AlertProperties alert property bag +type AlertProperties struct { + Essentials *Essentials `json:"essentials,omitempty"` + Context interface{} `json:"context,omitempty"` + EgressConfig interface{} `json:"egressConfig,omitempty"` +} + +// AlertsList list the alerts. +type AlertsList struct { + autorest.Response `json:"-"` + // NextLink - URL to fetch the next set of alerts. + NextLink *string `json:"nextLink,omitempty"` + // Value - List of alerts + Value *[]Alert `json:"value,omitempty"` +} + +// AlertsListIterator provides access to a complete listing of Alert values. +type AlertsListIterator struct { + i int + page AlertsListPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *AlertsListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *AlertsListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter AlertsListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter AlertsListIterator) Response() AlertsList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter AlertsListIterator) Value() Alert { + if !iter.page.NotDone() { + return Alert{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the AlertsListIterator type. +func NewAlertsListIterator(page AlertsListPage) AlertsListIterator { + return AlertsListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (al AlertsList) IsEmpty() bool { + return al.Value == nil || len(*al.Value) == 0 +} + +// alertsListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (al AlertsList) alertsListPreparer(ctx context.Context) (*http.Request, error) { + if al.NextLink == nil || len(to.String(al.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(al.NextLink))) +} + +// AlertsListPage contains a page of Alert values. +type AlertsListPage struct { + fn func(context.Context, AlertsList) (AlertsList, error) + al AlertsList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *AlertsListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AlertsListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.al) + if err != nil { + return err + } + page.al = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *AlertsListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page AlertsListPage) NotDone() bool { + return !page.al.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page AlertsListPage) Response() AlertsList { + return page.al +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page AlertsListPage) Values() []Alert { + if page.al.IsEmpty() { + return nil + } + return *page.al.Value +} + +// Creates a new instance of the AlertsListPage type. +func NewAlertsListPage(getNextPage func(context.Context, AlertsList) (AlertsList, error)) AlertsListPage { + return AlertsListPage{fn: getNextPage} +} + +// AlertsMetaData alert meta data information. +type AlertsMetaData struct { + autorest.Response `json:"-"` + Properties BasicAlertsMetaDataProperties `json:"properties,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for AlertsMetaData struct. +func (amd *AlertsMetaData) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + properties, err := unmarshalBasicAlertsMetaDataProperties(*v) + if err != nil { + return err + } + amd.Properties = properties + } + } + } + + return nil +} + +// BasicAlertsMetaDataProperties alert meta data property bag +type BasicAlertsMetaDataProperties interface { + AsMonitorServiceList() (*MonitorServiceList, bool) + AsAlertsMetaDataProperties() (*AlertsMetaDataProperties, bool) +} + +// AlertsMetaDataProperties alert meta data property bag +type AlertsMetaDataProperties struct { + // MetadataIdentifier - Possible values include: 'MetadataIdentifierAlertsMetaDataProperties', 'MetadataIdentifierMonitorServiceList' + MetadataIdentifier MetadataIdentifier `json:"metadataIdentifier,omitempty"` +} + +func unmarshalBasicAlertsMetaDataProperties(body []byte) (BasicAlertsMetaDataProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["metadataIdentifier"] { + case string(MetadataIdentifierMonitorServiceList): + var msl MonitorServiceList + err := json.Unmarshal(body, &msl) + return msl, err + default: + var amdp AlertsMetaDataProperties + err := json.Unmarshal(body, &amdp) + return amdp, err + } +} +func unmarshalBasicAlertsMetaDataPropertiesArray(body []byte) ([]BasicAlertsMetaDataProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + amdpArray := make([]BasicAlertsMetaDataProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + amdp, err := unmarshalBasicAlertsMetaDataProperties(*rawMessage) + if err != nil { + return nil, err + } + amdpArray[index] = amdp + } + return amdpArray, nil +} + +// MarshalJSON is the custom marshaler for AlertsMetaDataProperties. +func (amdp AlertsMetaDataProperties) MarshalJSON() ([]byte, error) { + amdp.MetadataIdentifier = MetadataIdentifierAlertsMetaDataProperties + objectMap := make(map[string]interface{}) + if amdp.MetadataIdentifier != "" { + objectMap["metadataIdentifier"] = amdp.MetadataIdentifier + } + return json.Marshal(objectMap) +} + +// AsMonitorServiceList is the BasicAlertsMetaDataProperties implementation for AlertsMetaDataProperties. +func (amdp AlertsMetaDataProperties) AsMonitorServiceList() (*MonitorServiceList, bool) { + return nil, false +} + +// AsAlertsMetaDataProperties is the BasicAlertsMetaDataProperties implementation for AlertsMetaDataProperties. +func (amdp AlertsMetaDataProperties) AsAlertsMetaDataProperties() (*AlertsMetaDataProperties, bool) { + return &amdp, true +} + +// AsBasicAlertsMetaDataProperties is the BasicAlertsMetaDataProperties implementation for AlertsMetaDataProperties. +func (amdp AlertsMetaDataProperties) AsBasicAlertsMetaDataProperties() (BasicAlertsMetaDataProperties, bool) { + return &amdp, true +} + +// AlertsSummary summary of alerts based on the input filters and 'groupby' parameters. +type AlertsSummary struct { + autorest.Response `json:"-"` + Properties *AlertsSummaryGroup `json:"properties,omitempty"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// AlertsSummaryGroup group the result set. +type AlertsSummaryGroup struct { + // Total - Total count of the result set. + Total *int32 `json:"total,omitempty"` + // SmartGroupsCount - Total count of the smart groups. + SmartGroupsCount *int32 `json:"smartGroupsCount,omitempty"` + // Groupedby - Name of the field aggregated + Groupedby *string `json:"groupedby,omitempty"` + // Values - List of the items + Values *[]AlertsSummaryGroupItem `json:"values,omitempty"` +} + +// AlertsSummaryGroupItem alerts summary group item +type AlertsSummaryGroupItem struct { + // Name - Value of the aggregated field + Name *string `json:"name,omitempty"` + // Count - Count of the aggregated field + Count *int32 `json:"count,omitempty"` + // Groupedby - Name of the field aggregated + Groupedby *string `json:"groupedby,omitempty"` + // Values - List of the items + Values *[]AlertsSummaryGroupItem `json:"values,omitempty"` +} + +// Bool ... +type Bool struct { + autorest.Response `json:"-"` + Value *bool `json:"value,omitempty"` +} + +// Condition condition to trigger an action rule +type Condition struct { + // Operator - operator for a given condition. Possible values include: 'Equals', 'NotEquals', 'Contains', 'DoesNotContain' + Operator Operator `json:"operator,omitempty"` + // Values - list of values to match for a given condition. + Values *[]string `json:"values,omitempty"` +} + +// Conditions conditions in alert instance to be matched for a given action rule. Default value is all. +// Multiple values could be provided with comma separation. +type Conditions struct { + // Severity - filter alerts by severity + Severity *Condition `json:"severity,omitempty"` + // MonitorService - filter alerts by monitor service + MonitorService *Condition `json:"monitorService,omitempty"` + // MonitorCondition - filter alerts by monitor condition + MonitorCondition *Condition `json:"monitorCondition,omitempty"` + // TargetResourceType - filter alerts by target resource type + TargetResourceType *Condition `json:"targetResourceType,omitempty"` + // AlertRuleID - filter alerts by alert rule id + AlertRuleID *Condition `json:"alertRuleId,omitempty"` + // Description - filter alerts by alert rule description + Description *Condition `json:"description,omitempty"` + // AlertContext - filter alerts by alert context (payload) + AlertContext *Condition `json:"alertContext,omitempty"` +} + +// Diagnostics action rule with diagnostics configuration +type Diagnostics struct { + // Scope - scope on which action rule will apply + Scope *Scope `json:"scope,omitempty"` + // Conditions - conditions on which alerts will be filtered + Conditions *Conditions `json:"conditions,omitempty"` + // Description - Description of action rule + Description *string `json:"description,omitempty"` + // CreatedAt - READ-ONLY; Creation time of action rule. Date-Time in ISO-8601 format. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // LastModifiedAt - READ-ONLY; Last updated time of action rule. Date-Time in ISO-8601 format. + LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` + // CreatedBy - READ-ONLY; Created by user name. + CreatedBy *string `json:"createdBy,omitempty"` + // LastModifiedBy - READ-ONLY; Last modified by user name. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + // Status - Indicates if the given action rule is enabled or disabled. Possible values include: 'Enabled', 'Disabled' + Status ActionRuleStatus `json:"status,omitempty"` + // Type - Possible values include: 'TypeActionRuleProperties', 'TypeSuppression', 'TypeActionGroup', 'TypeDiagnostics' + Type Type `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Diagnostics. +func (d Diagnostics) MarshalJSON() ([]byte, error) { + d.Type = TypeDiagnostics + objectMap := make(map[string]interface{}) + if d.Scope != nil { + objectMap["scope"] = d.Scope + } + if d.Conditions != nil { + objectMap["conditions"] = d.Conditions + } + if d.Description != nil { + objectMap["description"] = d.Description + } + if d.Status != "" { + objectMap["status"] = d.Status + } + if d.Type != "" { + objectMap["type"] = d.Type + } + return json.Marshal(objectMap) +} + +// AsSuppression is the BasicActionRuleProperties implementation for Diagnostics. +func (d Diagnostics) AsSuppression() (*Suppression, bool) { + return nil, false +} + +// AsActionGroup is the BasicActionRuleProperties implementation for Diagnostics. +func (d Diagnostics) AsActionGroup() (*ActionGroup, bool) { + return nil, false +} + +// AsDiagnostics is the BasicActionRuleProperties implementation for Diagnostics. +func (d Diagnostics) AsDiagnostics() (*Diagnostics, bool) { + return &d, true +} + +// AsActionRuleProperties is the BasicActionRuleProperties implementation for Diagnostics. +func (d Diagnostics) AsActionRuleProperties() (*ActionRuleProperties, bool) { + return nil, false +} + +// AsBasicActionRuleProperties is the BasicActionRuleProperties implementation for Diagnostics. +func (d Diagnostics) AsBasicActionRuleProperties() (BasicActionRuleProperties, bool) { + return &d, true +} + +// ErrorResponse an error response from the service. +type ErrorResponse struct { + Error *ErrorResponseBody `json:"error,omitempty"` +} + +// ErrorResponseBody details of error response. +type ErrorResponseBody struct { + // Code - Error code, intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - Description of the error, intended for display in user interface. + Message *string `json:"message,omitempty"` + // Target - Target of the particular error, for example name of the property. + Target *string `json:"target,omitempty"` + // Details - A list of additional details about the error. + Details *[]ErrorResponseBody `json:"details,omitempty"` +} + +// Essentials this object contains consistent fields across different monitor services. +type Essentials struct { + // Severity - READ-ONLY; Severity of alert Sev0 being highest and Sev4 being lowest. Possible values include: 'Sev0', 'Sev1', 'Sev2', 'Sev3', 'Sev4' + Severity Severity `json:"severity,omitempty"` + // SignalType - READ-ONLY; The type of signal the alert is based on, which could be metrics, logs or activity logs. Possible values include: 'Metric', 'Log', 'Unknown' + SignalType SignalType `json:"signalType,omitempty"` + // AlertState - READ-ONLY; Alert object state, which can be modified by the user. Possible values include: 'AlertStateNew', 'AlertStateAcknowledged', 'AlertStateClosed' + AlertState AlertState `json:"alertState,omitempty"` + // MonitorCondition - READ-ONLY; Condition of the rule at the monitor service. It represents whether the underlying conditions have crossed the defined alert rule thresholds. Possible values include: 'Fired', 'Resolved' + MonitorCondition MonitorCondition `json:"monitorCondition,omitempty"` + // TargetResource - Target ARM resource, on which alert got created. + TargetResource *string `json:"targetResource,omitempty"` + // TargetResourceName - Name of the target ARM resource name, on which alert got created. + TargetResourceName *string `json:"targetResourceName,omitempty"` + // TargetResourceGroup - Resource group of target ARM resource, on which alert got created. + TargetResourceGroup *string `json:"targetResourceGroup,omitempty"` + // TargetResourceType - Resource type of target ARM resource, on which alert got created. + TargetResourceType *string `json:"targetResourceType,omitempty"` + // MonitorService - READ-ONLY; Monitor service on which the rule(monitor) is set. Possible values include: 'ApplicationInsights', 'ActivityLogAdministrative', 'ActivityLogSecurity', 'ActivityLogRecommendation', 'ActivityLogPolicy', 'ActivityLogAutoscale', 'LogAnalytics', 'Nagios', 'Platform', 'SCOM', 'ServiceHealth', 'SmartDetector', 'VMInsights', 'Zabbix' + MonitorService MonitorService `json:"monitorService,omitempty"` + // AlertRule - READ-ONLY; Rule(monitor) which fired alert instance. Depending on the monitor service, this would be ARM id or name of the rule. + AlertRule *string `json:"alertRule,omitempty"` + // SourceCreatedID - READ-ONLY; Unique Id created by monitor service for each alert instance. This could be used to track the issue at the monitor service, in case of Nagios, Zabbix, SCOM etc. + SourceCreatedID *string `json:"sourceCreatedId,omitempty"` + // SmartGroupID - READ-ONLY; Unique Id of the smart group + SmartGroupID *string `json:"smartGroupId,omitempty"` + // SmartGroupingReason - READ-ONLY; Verbose reason describing the reason why this alert instance is added to a smart group + SmartGroupingReason *string `json:"smartGroupingReason,omitempty"` + // StartDateTime - READ-ONLY; Creation time(ISO-8601 format) of alert instance. + StartDateTime *date.Time `json:"startDateTime,omitempty"` + // LastModifiedDateTime - READ-ONLY; Last modification time(ISO-8601 format) of alert instance. + LastModifiedDateTime *date.Time `json:"lastModifiedDateTime,omitempty"` + // MonitorConditionResolvedDateTime - READ-ONLY; Resolved time(ISO-8601 format) of alert instance. This will be updated when monitor service resolves the alert instance because the rule condition is no longer met. + MonitorConditionResolvedDateTime *date.Time `json:"monitorConditionResolvedDateTime,omitempty"` + // LastModifiedUserName - READ-ONLY; User who last modified the alert, in case of monitor service updates user would be 'system', otherwise name of the user. + LastModifiedUserName *string `json:"lastModifiedUserName,omitempty"` +} + +// ManagedResource an azure managed resource object +type ManagedResource struct { + // Location - Resource location + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// MarshalJSON is the custom marshaler for ManagedResource. +func (mr ManagedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mr.Location != nil { + objectMap["location"] = mr.Location + } + if mr.Tags != nil { + objectMap["tags"] = mr.Tags + } + return json.Marshal(objectMap) +} + +// MonitorServiceDetails details of a monitor service +type MonitorServiceDetails struct { + // Name - Monitor service name + Name *string `json:"name,omitempty"` + // DisplayName - Monitor service display name + DisplayName *string `json:"displayName,omitempty"` +} + +// MonitorServiceList monitor service details +type MonitorServiceList struct { + // Data - Array of operations + Data *[]MonitorServiceDetails `json:"data,omitempty"` + // MetadataIdentifier - Possible values include: 'MetadataIdentifierAlertsMetaDataProperties', 'MetadataIdentifierMonitorServiceList' + MetadataIdentifier MetadataIdentifier `json:"metadataIdentifier,omitempty"` +} + +// MarshalJSON is the custom marshaler for MonitorServiceList. +func (msl MonitorServiceList) MarshalJSON() ([]byte, error) { + msl.MetadataIdentifier = MetadataIdentifierMonitorServiceList + objectMap := make(map[string]interface{}) + if msl.Data != nil { + objectMap["data"] = msl.Data + } + if msl.MetadataIdentifier != "" { + objectMap["metadataIdentifier"] = msl.MetadataIdentifier + } + return json.Marshal(objectMap) +} + +// AsMonitorServiceList is the BasicAlertsMetaDataProperties implementation for MonitorServiceList. +func (msl MonitorServiceList) AsMonitorServiceList() (*MonitorServiceList, bool) { + return &msl, true +} + +// AsAlertsMetaDataProperties is the BasicAlertsMetaDataProperties implementation for MonitorServiceList. +func (msl MonitorServiceList) AsAlertsMetaDataProperties() (*AlertsMetaDataProperties, bool) { + return nil, false +} + +// AsBasicAlertsMetaDataProperties is the BasicAlertsMetaDataProperties implementation for MonitorServiceList. +func (msl MonitorServiceList) AsBasicAlertsMetaDataProperties() (BasicAlertsMetaDataProperties, bool) { + return &msl, true +} + +// Operation operation provided by provider +type Operation struct { + // Name - Name of the operation + Name *string `json:"name,omitempty"` + // Display - Properties of the operation + Display *OperationDisplay `json:"display,omitempty"` +} + +// OperationDisplay properties of the operation +type OperationDisplay struct { + // Provider - Provider name + Provider *string `json:"provider,omitempty"` + // Resource - Resource name + Resource *string `json:"resource,omitempty"` + // Operation - Operation name + Operation *string `json:"operation,omitempty"` + // Description - Description of the operation + Description *string `json:"description,omitempty"` +} + +// OperationsList lists the operations available in the AlertsManagement RP. +type OperationsList struct { + autorest.Response `json:"-"` + // NextLink - URL to fetch the next set of alerts. + NextLink *string `json:"nextLink,omitempty"` + // Value - Array of operations + Value *[]Operation `json:"value,omitempty"` +} + +// OperationsListIterator provides access to a complete listing of Operation values. +type OperationsListIterator struct { + i int + page OperationsListPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *OperationsListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *OperationsListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OperationsListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter OperationsListIterator) Response() OperationsList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter OperationsListIterator) Value() Operation { + if !iter.page.NotDone() { + return Operation{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the OperationsListIterator type. +func NewOperationsListIterator(page OperationsListPage) OperationsListIterator { + return OperationsListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ol OperationsList) IsEmpty() bool { + return ol.Value == nil || len(*ol.Value) == 0 +} + +// operationsListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ol OperationsList) operationsListPreparer(ctx context.Context) (*http.Request, error) { + if ol.NextLink == nil || len(to.String(ol.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ol.NextLink))) +} + +// OperationsListPage contains a page of Operation values. +type OperationsListPage struct { + fn func(context.Context, OperationsList) (OperationsList, error) + ol OperationsList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OperationsListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.ol) + if err != nil { + return err + } + page.ol = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *OperationsListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OperationsListPage) NotDone() bool { + return !page.ol.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OperationsListPage) Response() OperationsList { + return page.ol +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OperationsListPage) Values() []Operation { + if page.ol.IsEmpty() { + return nil + } + return *page.ol.Value +} + +// Creates a new instance of the OperationsListPage type. +func NewOperationsListPage(getNextPage func(context.Context, OperationsList) (OperationsList, error)) OperationsListPage { + return OperationsListPage{fn: getNextPage} +} + +// PatchObject data contract for patch +type PatchObject struct { + // PatchProperties - properties supported by patch operation + *PatchProperties `json:"properties,omitempty"` + // Tags - tags to be updated + Tags interface{} `json:"tags,omitempty"` +} + +// MarshalJSON is the custom marshaler for PatchObject. +func (po PatchObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if po.PatchProperties != nil { + objectMap["properties"] = po.PatchProperties + } + if po.Tags != nil { + objectMap["tags"] = po.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PatchObject struct. +func (po *PatchObject) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var patchProperties PatchProperties + err = json.Unmarshal(*v, &patchProperties) + if err != nil { + return err + } + po.PatchProperties = &patchProperties + } + case "tags": + if v != nil { + var tags interface{} + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + po.Tags = tags + } + } + } + + return nil +} + +// PatchProperties action rule properties supported by patch +type PatchProperties struct { + // Status - Indicates if the given action rule is enabled or disabled. Possible values include: 'Enabled', 'Disabled' + Status ActionRuleStatus `json:"status,omitempty"` +} + +// Resource an azure resource object +type Resource struct { + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// Scope target scope for a given action rule. By default scope will be the subscription. User can also +// provide list of resource groups or list of resources from the scope subscription as well. +type Scope struct { + // ScopeType - type of target scope. Possible values include: 'ScopeTypeResourceGroup', 'ScopeTypeResource' + ScopeType ScopeType `json:"scopeType,omitempty"` + // Values - list of ARM IDs of the given scope type which will be the target of the given action rule. + Values *[]string `json:"values,omitempty"` +} + +// SmartGroup set of related alerts grouped together smartly by AMS. +type SmartGroup struct { + autorest.Response `json:"-"` + *SmartGroupProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// MarshalJSON is the custom marshaler for SmartGroup. +func (sg SmartGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sg.SmartGroupProperties != nil { + objectMap["properties"] = sg.SmartGroupProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SmartGroup struct. +func (sg *SmartGroup) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var smartGroupProperties SmartGroupProperties + err = json.Unmarshal(*v, &smartGroupProperties) + if err != nil { + return err + } + sg.SmartGroupProperties = &smartGroupProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sg.ID = &ID + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sg.Type = &typeVar + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sg.Name = &name + } + } + } + + return nil +} + +// SmartGroupAggregatedProperty aggregated property of each type +type SmartGroupAggregatedProperty struct { + // Name - Name of the type. + Name *string `json:"name,omitempty"` + // Count - Total number of items of type. + Count *int32 `json:"count,omitempty"` +} + +// SmartGroupModification alert Modification details +type SmartGroupModification struct { + autorest.Response `json:"-"` + Properties *SmartGroupModificationProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty"` + // Type - READ-ONLY; Azure resource type + Type *string `json:"type,omitempty"` + // Name - READ-ONLY; Azure resource name + Name *string `json:"name,omitempty"` +} + +// SmartGroupModificationItem smartGroup modification item. +type SmartGroupModificationItem struct { + // ModificationEvent - Reason for the modification. Possible values include: 'SmartGroupModificationEventSmartGroupCreated', 'SmartGroupModificationEventStateChange', 'SmartGroupModificationEventAlertAdded', 'SmartGroupModificationEventAlertRemoved' + ModificationEvent SmartGroupModificationEvent `json:"modificationEvent,omitempty"` + // OldValue - Old value + OldValue *string `json:"oldValue,omitempty"` + // NewValue - New value + NewValue *string `json:"newValue,omitempty"` + // ModifiedAt - Modified date and time + ModifiedAt *string `json:"modifiedAt,omitempty"` + // ModifiedBy - Modified user details (Principal client name) + ModifiedBy *string `json:"modifiedBy,omitempty"` + // Comments - Modification comments + Comments *string `json:"comments,omitempty"` + // Description - Description of the modification + Description *string `json:"description,omitempty"` +} + +// SmartGroupModificationProperties properties of the smartGroup modification item. +type SmartGroupModificationProperties struct { + // SmartGroupID - READ-ONLY; Unique Id of the smartGroup for which the history is being retrieved + SmartGroupID *string `json:"smartGroupId,omitempty"` + // Modifications - Modification details + Modifications *[]SmartGroupModificationItem `json:"modifications,omitempty"` + // NextLink - URL to fetch the next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// SmartGroupProperties properties of smart group. +type SmartGroupProperties struct { + // AlertsCount - Total number of alerts in smart group + AlertsCount *int32 `json:"alertsCount,omitempty"` + // SmartGroupState - READ-ONLY; Smart group state. Possible values include: 'StateNew', 'StateAcknowledged', 'StateClosed' + SmartGroupState State `json:"smartGroupState,omitempty"` + // Severity - READ-ONLY; Severity of smart group is the highest(Sev0 >... > Sev4) severity of all the alerts in the group. Possible values include: 'Sev0', 'Sev1', 'Sev2', 'Sev3', 'Sev4' + Severity Severity `json:"severity,omitempty"` + // StartDateTime - READ-ONLY; Creation time of smart group. Date-Time in ISO-8601 format. + StartDateTime *date.Time `json:"startDateTime,omitempty"` + // LastModifiedDateTime - READ-ONLY; Last updated time of smart group. Date-Time in ISO-8601 format. + LastModifiedDateTime *date.Time `json:"lastModifiedDateTime,omitempty"` + // LastModifiedUserName - READ-ONLY; Last modified by user name. + LastModifiedUserName *string `json:"lastModifiedUserName,omitempty"` + // Resources - Summary of target resources in the smart group + Resources *[]SmartGroupAggregatedProperty `json:"resources,omitempty"` + // ResourceTypes - Summary of target resource types in the smart group + ResourceTypes *[]SmartGroupAggregatedProperty `json:"resourceTypes,omitempty"` + // ResourceGroups - Summary of target resource groups in the smart group + ResourceGroups *[]SmartGroupAggregatedProperty `json:"resourceGroups,omitempty"` + // MonitorServices - Summary of monitorServices in the smart group + MonitorServices *[]SmartGroupAggregatedProperty `json:"monitorServices,omitempty"` + // MonitorConditions - Summary of monitorConditions in the smart group + MonitorConditions *[]SmartGroupAggregatedProperty `json:"monitorConditions,omitempty"` + // AlertStates - Summary of alertStates in the smart group + AlertStates *[]SmartGroupAggregatedProperty `json:"alertStates,omitempty"` + // AlertSeverities - Summary of alertSeverities in the smart group + AlertSeverities *[]SmartGroupAggregatedProperty `json:"alertSeverities,omitempty"` + // NextLink - The URI to fetch the next page of alerts. Call ListNext() with this URI to fetch the next page alerts. + NextLink *string `json:"nextLink,omitempty"` +} + +// SmartGroupsList list the alerts. +type SmartGroupsList struct { + autorest.Response `json:"-"` + // NextLink - URL to fetch the next set of alerts. + NextLink *string `json:"nextLink,omitempty"` + // Value - List of alerts + Value *[]SmartGroup `json:"value,omitempty"` +} + +// SmartGroupsListIterator provides access to a complete listing of SmartGroup values. +type SmartGroupsListIterator struct { + i int + page SmartGroupsListPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *SmartGroupsListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *SmartGroupsListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SmartGroupsListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter SmartGroupsListIterator) Response() SmartGroupsList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter SmartGroupsListIterator) Value() SmartGroup { + if !iter.page.NotDone() { + return SmartGroup{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the SmartGroupsListIterator type. +func NewSmartGroupsListIterator(page SmartGroupsListPage) SmartGroupsListIterator { + return SmartGroupsListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (sgl SmartGroupsList) IsEmpty() bool { + return sgl.Value == nil || len(*sgl.Value) == 0 +} + +// smartGroupsListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sgl SmartGroupsList) smartGroupsListPreparer(ctx context.Context) (*http.Request, error) { + if sgl.NextLink == nil || len(to.String(sgl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sgl.NextLink))) +} + +// SmartGroupsListPage contains a page of SmartGroup values. +type SmartGroupsListPage struct { + fn func(context.Context, SmartGroupsList) (SmartGroupsList, error) + sgl SmartGroupsList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *SmartGroupsListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.sgl) + if err != nil { + return err + } + page.sgl = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *SmartGroupsListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SmartGroupsListPage) NotDone() bool { + return !page.sgl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SmartGroupsListPage) Response() SmartGroupsList { + return page.sgl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SmartGroupsListPage) Values() []SmartGroup { + if page.sgl.IsEmpty() { + return nil + } + return *page.sgl.Value +} + +// Creates a new instance of the SmartGroupsListPage type. +func NewSmartGroupsListPage(getNextPage func(context.Context, SmartGroupsList) (SmartGroupsList, error)) SmartGroupsListPage { + return SmartGroupsListPage{fn: getNextPage} +} + +// Suppression action rule with suppression configuration +type Suppression struct { + // SuppressionConfig - suppression configuration for the action rule + SuppressionConfig *SuppressionConfig `json:"suppressionConfig,omitempty"` + // Scope - scope on which action rule will apply + Scope *Scope `json:"scope,omitempty"` + // Conditions - conditions on which alerts will be filtered + Conditions *Conditions `json:"conditions,omitempty"` + // Description - Description of action rule + Description *string `json:"description,omitempty"` + // CreatedAt - READ-ONLY; Creation time of action rule. Date-Time in ISO-8601 format. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // LastModifiedAt - READ-ONLY; Last updated time of action rule. Date-Time in ISO-8601 format. + LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` + // CreatedBy - READ-ONLY; Created by user name. + CreatedBy *string `json:"createdBy,omitempty"` + // LastModifiedBy - READ-ONLY; Last modified by user name. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + // Status - Indicates if the given action rule is enabled or disabled. Possible values include: 'Enabled', 'Disabled' + Status ActionRuleStatus `json:"status,omitempty"` + // Type - Possible values include: 'TypeActionRuleProperties', 'TypeSuppression', 'TypeActionGroup', 'TypeDiagnostics' + Type Type `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Suppression. +func (s Suppression) MarshalJSON() ([]byte, error) { + s.Type = TypeSuppression + objectMap := make(map[string]interface{}) + if s.SuppressionConfig != nil { + objectMap["suppressionConfig"] = s.SuppressionConfig + } + if s.Scope != nil { + objectMap["scope"] = s.Scope + } + if s.Conditions != nil { + objectMap["conditions"] = s.Conditions + } + if s.Description != nil { + objectMap["description"] = s.Description + } + if s.Status != "" { + objectMap["status"] = s.Status + } + if s.Type != "" { + objectMap["type"] = s.Type + } + return json.Marshal(objectMap) +} + +// AsSuppression is the BasicActionRuleProperties implementation for Suppression. +func (s Suppression) AsSuppression() (*Suppression, bool) { + return &s, true +} + +// AsActionGroup is the BasicActionRuleProperties implementation for Suppression. +func (s Suppression) AsActionGroup() (*ActionGroup, bool) { + return nil, false +} + +// AsDiagnostics is the BasicActionRuleProperties implementation for Suppression. +func (s Suppression) AsDiagnostics() (*Diagnostics, bool) { + return nil, false +} + +// AsActionRuleProperties is the BasicActionRuleProperties implementation for Suppression. +func (s Suppression) AsActionRuleProperties() (*ActionRuleProperties, bool) { + return nil, false +} + +// AsBasicActionRuleProperties is the BasicActionRuleProperties implementation for Suppression. +func (s Suppression) AsBasicActionRuleProperties() (BasicActionRuleProperties, bool) { + return &s, true +} + +// SuppressionConfig suppression logic for a given action rule +type SuppressionConfig struct { + // RecurrenceType - Specifies when the suppression should be applied. Possible values include: 'Always', 'Once', 'Daily', 'Weekly', 'Monthly' + RecurrenceType SuppressionType `json:"recurrenceType,omitempty"` + // Schedule - suppression schedule configuration + Schedule *SuppressionSchedule `json:"schedule,omitempty"` +} + +// SuppressionSchedule schedule for a given suppression configuration. +type SuppressionSchedule struct { + // StartDate - Start date for suppression + StartDate *string `json:"startDate,omitempty"` + // EndDate - End date for suppression + EndDate *string `json:"endDate,omitempty"` + // StartTime - Start time for suppression + StartTime *string `json:"startTime,omitempty"` + // EndTime - End date for suppression + EndTime *string `json:"endTime,omitempty"` + // RecurrenceValues - Specifies the values for recurrence pattern + RecurrenceValues *[]int32 `json:"recurrenceValues,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/operations.go new file mode 100644 index 000000000000..269a0ff01d10 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/operations.go @@ -0,0 +1,147 @@ +package alertsmanagement + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// OperationsClient is the alertsManagement Client +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List list all operations available through Azure Alerts Management Resource Provider. +func (client OperationsClient) List(ctx context.Context) (result OperationsListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.ol.Response.Response != nil { + sc = result.ol.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.ol.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.ol, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.AlertsManagement/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationsList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client OperationsClient) listNextResults(ctx context.Context, lastResults OperationsList) (result OperationsList, err error) { + req, err := lastResults.operationsListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "alertsmanagement.OperationsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "alertsmanagement.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.OperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OperationsClient) ListComplete(ctx context.Context) (result OperationsListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/smartgroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/smartgroups.go new file mode 100644 index 000000000000..3a21830eddb5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/smartgroups.go @@ -0,0 +1,448 @@ +package alertsmanagement + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// SmartGroupsClient is the alertsManagement Client +type SmartGroupsClient struct { + BaseClient +} + +// NewSmartGroupsClient creates an instance of the SmartGroupsClient client. +func NewSmartGroupsClient(subscriptionID string) SmartGroupsClient { + return NewSmartGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSmartGroupsClientWithBaseURI creates an instance of the SmartGroupsClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewSmartGroupsClientWithBaseURI(baseURI string, subscriptionID string) SmartGroupsClient { + return SmartGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ChangeState change the state of a Smart Group. +// Parameters: +// smartGroupID - smart group unique id. +// newState - new state of the alert. +func (client SmartGroupsClient) ChangeState(ctx context.Context, smartGroupID string, newState AlertState) (result SmartGroup, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsClient.ChangeState") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.SmartGroupsClient", "ChangeState", err.Error()) + } + + req, err := client.ChangeStatePreparer(ctx, smartGroupID, newState) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "ChangeState", nil, "Failure preparing request") + return + } + + resp, err := client.ChangeStateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "ChangeState", resp, "Failure sending request") + return + } + + result, err = client.ChangeStateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "ChangeState", resp, "Failure responding to request") + } + + return +} + +// ChangeStatePreparer prepares the ChangeState request. +func (client SmartGroupsClient) ChangeStatePreparer(ctx context.Context, smartGroupID string, newState AlertState) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "smartGroupId": autorest.Encode("path", smartGroupID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + "newState": autorest.Encode("query", newState), + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/changeState", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ChangeStateSender sends the ChangeState request. The method will close the +// http.Response Body if it receives an error. +func (client SmartGroupsClient) ChangeStateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ChangeStateResponder handles the response to the ChangeState request. The method always +// closes the http.Response Body. +func (client SmartGroupsClient) ChangeStateResponder(resp *http.Response) (result SmartGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetAll list all the Smart Groups within a specified subscription. +// Parameters: +// targetResource - filter by target resource( which is full ARM ID) Default value is select all. +// targetResourceGroup - filter by target resource group name. Default value is select all. +// targetResourceType - filter by target resource type. Default value is select all. +// monitorService - filter by monitor service which generates the alert instance. Default value is select all. +// monitorCondition - filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to +// select all. +// severity - filter by severity. Default value is select all. +// smartGroupState - filter by state of the smart group. Default value is to select all. +// timeRange - filter by time range by below listed values. Default value is 1 day. +// pageCount - determines number of alerts returned per page in response. Permissible value is between 1 to +// 250. When the "includeContent" filter is selected, maximum value allowed is 25. Default value is 25. +// sortBy - sort the query results by input field. Default value is sort by 'lastModifiedDateTime'. +// sortOrder - sort the query results order in either ascending or descending. Default value is 'desc' for +// time fields and 'asc' for others. +func (client SmartGroupsClient) GetAll(ctx context.Context, targetResource string, targetResourceGroup string, targetResourceType string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, smartGroupState AlertState, timeRange TimeRange, pageCount *int32, sortBy SmartGroupsSortByFields, sortOrder string) (result SmartGroupsListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsClient.GetAll") + defer func() { + sc := -1 + if result.sgl.Response.Response != nil { + sc = result.sgl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.SmartGroupsClient", "GetAll", err.Error()) + } + + result.fn = client.getAllNextResults + req, err := client.GetAllPreparer(ctx, targetResource, targetResourceGroup, targetResourceType, monitorService, monitorCondition, severity, smartGroupState, timeRange, pageCount, sortBy, sortOrder) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetAll", nil, "Failure preparing request") + return + } + + resp, err := client.GetAllSender(req) + if err != nil { + result.sgl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetAll", resp, "Failure sending request") + return + } + + result.sgl, err = client.GetAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetAll", resp, "Failure responding to request") + } + + return +} + +// GetAllPreparer prepares the GetAll request. +func (client SmartGroupsClient) GetAllPreparer(ctx context.Context, targetResource string, targetResourceGroup string, targetResourceType string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, smartGroupState AlertState, timeRange TimeRange, pageCount *int32, sortBy SmartGroupsSortByFields, sortOrder string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(targetResource) > 0 { + queryParameters["targetResource"] = autorest.Encode("query", targetResource) + } + if len(targetResourceGroup) > 0 { + queryParameters["targetResourceGroup"] = autorest.Encode("query", targetResourceGroup) + } + if len(targetResourceType) > 0 { + queryParameters["targetResourceType"] = autorest.Encode("query", targetResourceType) + } + if len(string(monitorService)) > 0 { + queryParameters["monitorService"] = autorest.Encode("query", monitorService) + } + if len(string(monitorCondition)) > 0 { + queryParameters["monitorCondition"] = autorest.Encode("query", monitorCondition) + } + if len(string(severity)) > 0 { + queryParameters["severity"] = autorest.Encode("query", severity) + } + if len(string(smartGroupState)) > 0 { + queryParameters["smartGroupState"] = autorest.Encode("query", smartGroupState) + } + if len(string(timeRange)) > 0 { + queryParameters["timeRange"] = autorest.Encode("query", timeRange) + } + if pageCount != nil { + queryParameters["pageCount"] = autorest.Encode("query", *pageCount) + } + if len(string(sortBy)) > 0 { + queryParameters["sortBy"] = autorest.Encode("query", sortBy) + } + if len(string(sortOrder)) > 0 { + queryParameters["sortOrder"] = autorest.Encode("query", sortOrder) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetAllSender sends the GetAll request. The method will close the +// http.Response Body if it receives an error. +func (client SmartGroupsClient) GetAllSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetAllResponder handles the response to the GetAll request. The method always +// closes the http.Response Body. +func (client SmartGroupsClient) GetAllResponder(resp *http.Response) (result SmartGroupsList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// getAllNextResults retrieves the next set of results, if any. +func (client SmartGroupsClient) getAllNextResults(ctx context.Context, lastResults SmartGroupsList) (result SmartGroupsList, err error) { + req, err := lastResults.smartGroupsListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "getAllNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.GetAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "getAllNextResults", resp, "Failure sending next results request") + } + result, err = client.GetAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "getAllNextResults", resp, "Failure responding to next results request") + } + return +} + +// GetAllComplete enumerates all values, automatically crossing page boundaries as required. +func (client SmartGroupsClient) GetAllComplete(ctx context.Context, targetResource string, targetResourceGroup string, targetResourceType string, monitorService MonitorService, monitorCondition MonitorCondition, severity Severity, smartGroupState AlertState, timeRange TimeRange, pageCount *int32, sortBy SmartGroupsSortByFields, sortOrder string) (result SmartGroupsListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsClient.GetAll") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.GetAll(ctx, targetResource, targetResourceGroup, targetResourceType, monitorService, monitorCondition, severity, smartGroupState, timeRange, pageCount, sortBy, sortOrder) + return +} + +// GetByID get information related to a specific Smart Group. +// Parameters: +// smartGroupID - smart group unique id. +func (client SmartGroupsClient) GetByID(ctx context.Context, smartGroupID string) (result SmartGroup, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsClient.GetByID") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.SmartGroupsClient", "GetByID", err.Error()) + } + + req, err := client.GetByIDPreparer(ctx, smartGroupID) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetByID", nil, "Failure preparing request") + return + } + + resp, err := client.GetByIDSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetByID", resp, "Failure sending request") + return + } + + result, err = client.GetByIDResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetByID", resp, "Failure responding to request") + } + + return +} + +// GetByIDPreparer prepares the GetByID request. +func (client SmartGroupsClient) GetByIDPreparer(ctx context.Context, smartGroupID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "smartGroupId": autorest.Encode("path", smartGroupID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetByIDSender sends the GetByID request. The method will close the +// http.Response Body if it receives an error. +func (client SmartGroupsClient) GetByIDSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetByIDResponder handles the response to the GetByID request. The method always +// closes the http.Response Body. +func (client SmartGroupsClient) GetByIDResponder(resp *http.Response) (result SmartGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetHistory get the history a smart group, which captures any Smart Group state changes (New/Acknowledged/Closed) . +// Parameters: +// smartGroupID - smart group unique id. +func (client SmartGroupsClient) GetHistory(ctx context.Context, smartGroupID string) (result SmartGroupModification, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SmartGroupsClient.GetHistory") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: client.SubscriptionID, + Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("alertsmanagement.SmartGroupsClient", "GetHistory", err.Error()) + } + + req, err := client.GetHistoryPreparer(ctx, smartGroupID) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetHistory", nil, "Failure preparing request") + return + } + + resp, err := client.GetHistorySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetHistory", resp, "Failure sending request") + return + } + + result, err = client.GetHistoryResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "alertsmanagement.SmartGroupsClient", "GetHistory", resp, "Failure responding to request") + } + + return +} + +// GetHistoryPreparer prepares the GetHistory request. +func (client SmartGroupsClient) GetHistoryPreparer(ctx context.Context, smartGroupID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "smartGroupId": autorest.Encode("path", smartGroupID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-05-05-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/history", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetHistorySender sends the GetHistory request. The method will close the +// http.Response Body if it receives an error. +func (client SmartGroupsClient) GetHistorySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetHistoryResponder handles the response to the GetHistory request. The method always +// closes the http.Response Body. +func (client SmartGroupsClient) GetHistoryResponder(resp *http.Response) (result SmartGroupModification, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/version.go new file mode 100644 index 000000000000..b5cf618b1527 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement/version.go @@ -0,0 +1,30 @@ +package alertsmanagement + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + Version() + " alertsmanagement/2019-05-05-preview" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/modules.txt b/vendor/modules.txt index af7dbaadc686..0b58fe2c42af 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -53,6 +53,7 @@ github.com/Azure/azure-sdk-for-go/services/notificationhubs/mgmt/2017-04-01/noti github.com/Azure/azure-sdk-for-go/services/policyinsights/mgmt/2019-10-01/policyinsights github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2017-12-01/postgresql github.com/Azure/azure-sdk-for-go/services/powerbidedicated/mgmt/2017-10-01/powerbidedicated +github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-05-05/alertsmanagement github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2019-05-01-preview/appplatform github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-09-01-preview/authorization github.com/Azure/azure-sdk-for-go/services/preview/botservice/mgmt/2018-07-12/botservice diff --git a/website/azurerm.erb b/website/azurerm.erb index b8d309844bd7..a303a46e9758 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -1920,6 +1920,14 @@ azurerm_monitor_action_group +
  • + azurerm_monitor_action_rule_action_group +
  • + +
  • + azurerm_monitor_action_rule_suppression +
  • +
  • azurerm_monitor_activity_log_alert
  • diff --git a/website/docs/r/monitor_action_rule_action_group.html.markdown b/website/docs/r/monitor_action_rule_action_group.html.markdown new file mode 100644 index 000000000000..4e1fcae46673 --- /dev/null +++ b/website/docs/r/monitor_action_rule_action_group.html.markdown @@ -0,0 +1,168 @@ +--- +subcategory: "Monitor" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_monitor_action_rule_action_group" +description: |- + Manages an Monitor Action Rule which type is action group. +--- + +# azurerm_monitor_action_rule_action_group + +Manages an Monitor Action Rule which type is action group. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_monitor_action_group" "example" { + name = "example-action-group" + resource_group_name = azurerm_resource_group.example.name + short_name = "exampleactiongroup" +} + +resource "azurerm_monitor_action_rule_action_group" "example" { + name = "example-amar" + resource_group_name = azurerm_resource_group.example.name + action_group_id = azurerm_monitor_action_group.example.id + + scope { + type = "ResourceGroup" + resource_ids = [azurerm_resource_group.example.id] + } + + tags = { + foo = "bar" + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the Monitor Action Rule. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) Specifies the name of the resource group in which the Monitor Action Rule should exist. Changing this forces a new resource to be created. + +* `action_group_id` - (Required) Specifies the resource id of monitor action group. + +* `description` - (Optional) Specifies a description for the Action Rule. + +* `enabled` - (Optional) Is the Action Rule enabled? Defaults to `true`. + +* `scope` - (Optional) A `scope` block as defined below. + +* `condition` - (Optional) A `condition` block as defined below. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +--- + +The `scope` block supports the following: + +* `type` - (Required) Specifies the type of target scope. Possible values are `ResourceGroup` and `Resource`. + +* `resource_ids` - (Required) A list of resource IDs of the given scope type which will be the target of action rule. + +--- + +The `condition` block supports the following: + +* `alert_context` - (Optional) A `alert_context` block as defined below. + +* `alert_rule_id` - (Optional) A `alert_rule_id` block as defined below. + +* `description` - (Optional) A `description` block as defined below. + +* `monitor` - (Optional) A `monitor` block as defined below. + +* `monitor_service` - (Optional) A `monitor_service` as block defined below. + +* `severity` - (Optional) A `severity` block as defined below. + +* `target_resource_type` - (Optional) A `target_resource_type` block as defined below. + +--- + +The `alert_context` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`, `NotEquals`, `Contains`, and `DoesNotContain`. + +* `values` - (Required) A list of values to match for a given condition. + +--- + +The `alert_rule_id` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`, `NotEquals`, `Contains`, and `DoesNotContain`. + +* `values` - (Required) A list of values to match for a given condition. + +--- + +The `description` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`, `NotEquals`, `Contains`, and `DoesNotContain`. + +* `values` - (Required) A list of values to match for a given condition. + +--- + +The `monitor` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals` and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. Possible values are `Fired` and `Resolved`. + +--- + +The `monitor_service` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals` and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. Possible values are `ActivityLog Administrative`, `ActivityLog Autoscale`, `ActivityLog Policy`, `ActivityLog Recommendation`, `ActivityLog Security`, `Application Insights`, `Azure Backup`, `Data Box Edge`, `Data Box Gateway`, `Health Platform`, `Log Analytics`, `Platform`, and `Resource Health`. + +--- + +The `severity` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. Possible values are `Sev0`, `Sev1`, `Sev2`, `Sev3`, and `Sev4`. + +--- + +The `target_resource_type` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals` and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. The values should be valid resource types. + +--- + +## Attributes Reference + +The following attributes are exported: + +* `id` - The ID of the Monitor Action Rule. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Monitor Action Rule. +* `read` - (Defaults to 5 minutes) Used when retrieving the Monitor Action Rule. +* `update` - (Defaults to 30 minutes) Used when updating the Monitor Action Rule. +* `delete` - (Defaults to 30 minutes) Used when deleting the Monitor Action Rule. + +## Import + +Monitor Action Rule can be imported using the `resource id`, e.g. + +```shell +$ terraform import azurerm_monitor_action_rule_action_group.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AlertsManagement/actionRules/actionRule1 +``` diff --git a/website/docs/r/monitor_action_rule_suppression.html.markdown b/website/docs/r/monitor_action_rule_suppression.html.markdown new file mode 100644 index 000000000000..0075c3a75410 --- /dev/null +++ b/website/docs/r/monitor_action_rule_suppression.html.markdown @@ -0,0 +1,191 @@ +--- +subcategory: "Monitor" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_monitor_action_rule_suppression" +description: |- + Manages an Monitor Action Rule which type is suppression. +--- + +# azurerm_monitor_action_rule_suppression + +Manages an Monitor Action Rule which type is suppression. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_monitor_action_rule_suppression" "example" { + name = "example-amar" + resource_group_name = azurerm_resource_group.example.name + + scope { + type = "ResourceGroup" + resource_ids = [azurerm_resource_group.example.id] + } + + suppression { + recurrence_type = "Weekly" + + schedule { + start_date_utc = "2019-01-01T01:02:03Z" + end_date_utc = "2019-01-03T15:02:07Z" + recurrence_weekly = ["Sunday", "Monday", "Friday", "Saturday"] + } + } + + tags = { + foo = "bar" + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the Monitor Action Rule. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) Specifies the name of the resource group in which the Monitor Action Rule should exist. Changing this forces a new resource to be created. + +* `suppression` - (Required) A `suppression` block as defined below. + +* `description` - (Optional) Specifies a description for the Action Rule. + +* `enabled` - (Optional) Is the Action Rule enabled? Defaults to `true`. + +* `scope` - (Optional) A `scope` block as defined below. + +* `condition` - (Optional) A `condition` block as defined below. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +--- + +The `suppression` block supports the following: + +* `recurrence_type` - (Required) Specifies the type of suppression. Possible values are `Always`, `Daily`, `Monthly`, `Once`, and `Weekly`. + +* `schedule` - (Optional) A `schedule` block as defined below. Required if `recurrence_type` is `Daily`, `Monthly`, `Once` or `Weekly`. + +--- + +The `schedule` block supports the following: + +* `start_date_utc` - (Required) specifies the recurrence UTC start datetime (Y-m-d'T'H:M:S'Z'). + +* `end_date_utc` - (Required) specifies the recurrence UTC end datetime (Y-m-d'T'H:M:S'Z'). + +* `recurrence_weekly` - (Optional) specifies the list of dayOfWeek to recurrence. Possible values are `Sunday`, `Monday`, `Tuesday`, `Wednesday`, `Thursday`, `Friday` and `Saturday`. + +* `recurrence_monthly` - (Optional) specifies the list of dayOfMonth to recurrence. Possible values are between `1` - `31`. Required if `recurrence_type` is `Monthly`. + +--- + +The `scope` block supports the following: + +* `type` - (Required) Specifies the type of target scope. Possible values are `ResourceGroup` and `Resource`. + +* `resource_ids` - (Required) A list of resource IDs of the given scope type which will be the target of action rule. + +--- + +The `condition` block supports the following: + +* `alert_context` - (Optional) A `alert_context` block as defined below. + +* `alert_rule_id` - (Optional) A `alert_rule_id` block as defined below. + +* `description` - (Optional) A `description` block as defined below. + +* `monitor` - (Optional) A `monitor` block as defined below. + +* `monitor_service` - (Optional) A `monitor_service` as block defined below. + +* `severity` - (Optional) A `severity` block as defined below. + +* `target_resource_type` - (Optional) A `target_resource_type` block as defined below. + +--- + +The `alert_context` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`, `NotEquals`, `Contains`, and `DoesNotContain`. + +* `values` - (Required) A list of values to match for a given condition. + +--- + +The `alert_rule_id` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`, `NotEquals`, `Contains`, and `DoesNotContain`. + +* `values` - (Required) A list of values to match for a given condition. + +--- + +The `description` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`, `NotEquals`, `Contains`, and `DoesNotContain`. + +* `values` - (Required) A list of values to match for a given condition. + +--- + +The `monitor` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals` and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. Possible values are `Fired` and `Resolved`. + +--- + +The `monitor_service` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals` and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. Possible values are `ActivityLog Administrative`, `ActivityLog Autoscale`, `ActivityLog Policy`, `ActivityLog Recommendation`, `ActivityLog Security`, `Application Insights`, `Azure Backup`, `Data Box Edge`, `Data Box Gateway`, `Health Platform`, `Log Analytics`, `Platform`, and `Resource Health`. + +--- + +The `severity` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals`and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. Possible values are `Sev0`, `Sev1`, `Sev2`, `Sev3`, and `Sev4`. + +--- + +The `target_resource_type` block supports the following: + +* `operator` - (Required) The operator for a given condition. Possible values are `Equals` and `NotEquals`. + +* `values` - (Required) A list of values to match for a given condition. The values should be valid resource types. + +--- + +## Attributes Reference + +The following attributes are exported: + +* `id` - The ID of the Monitor Action Rule. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Monitor Action Rule. +* `read` - (Defaults to 5 minutes) Used when retrieving the Monitor Action Rule. +* `update` - (Defaults to 30 minutes) Used when updating the Monitor Action Rule. +* `delete` - (Defaults to 30 minutes) Used when deleting the Monitor Action Rule. + +## Import + +Monitor Action Rule can be imported using the `resource id`, e.g. + +```shell +$ terraform import azurerm_monitor_action_rule_suppression.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AlertsManagement/actionRules/actionRule1 +```