diff --git a/alicloud/data_source_alicloud_arms_notification_policies.go b/alicloud/data_source_alicloud_arms_notification_policies.go new file mode 100644 index 000000000000..10459bf9058b --- /dev/null +++ b/alicloud/data_source_alicloud_arms_notification_policies.go @@ -0,0 +1,425 @@ +package alicloud + +import ( + "fmt" + "regexp" + "time" + + "github.com/PaesslerAG/jsonpath" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +) + +func dataSourceAlicloudArmsNotificationPolicies() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAlicloudArmsNotificationPoliciesRead, + Schema: map[string]*schema.Schema{ + "ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "name_regex": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringIsValidRegExp, + }, + "names": { + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "enable_details": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "output_file": { + Type: schema.TypeString, + Optional: true, + }, + "policies": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "state": { + Type: schema.TypeString, + Computed: true, + }, + "repeat": { + Type: schema.TypeBool, + Computed: true, + }, + "repeat_interval": { + Type: schema.TypeInt, + Computed: true, + }, + "send_recover_message": { + Type: schema.TypeBool, + Computed: true, + }, + "escalation_policy_id": { + Type: schema.TypeInt, + Computed: true, + }, + "integration_id": { + Type: schema.TypeInt, + Computed: true, + }, + "directed_mode": { + Type: schema.TypeBool, + Computed: true, + }, + "group_rule": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "group_wait": { + Type: schema.TypeInt, + Computed: true, + }, + "group_interval": { + Type: schema.TypeInt, + Computed: true, + }, + "grouping_fields": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + "matching_rules": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "matching_conditions": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Computed: true, + }, + "value": { + Type: schema.TypeString, + Computed: true, + }, + "operator": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "notify_rule": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "notify_start_time": { + Type: schema.TypeString, + Computed: true, + }, + "notify_end_time": { + Type: schema.TypeString, + Computed: true, + }, + "notify_channels": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "notify_objects": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "notify_object_type": { + Type: schema.TypeString, + Computed: true, + }, + "notify_object_id": { + Type: schema.TypeString, + Computed: true, + }, + "notify_object_name": { + Type: schema.TypeString, + Computed: true, + }, + "notify_channels": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + }, + }, + }, + "notify_template": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "email_title": { + Type: schema.TypeString, + Computed: true, + }, + "email_content": { + Type: schema.TypeString, + Computed: true, + }, + "email_recover_title": { + Type: schema.TypeString, + Computed: true, + }, + "email_recover_content": { + Type: schema.TypeString, + Computed: true, + }, + "sms_content": { + Type: schema.TypeString, + Computed: true, + }, + "sms_recover_content": { + Type: schema.TypeString, + Computed: true, + }, + "tts_content": { + Type: schema.TypeString, + Computed: true, + }, + "tts_recover_content": { + Type: schema.TypeString, + Computed: true, + }, + "robot_content": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceAlicloudArmsNotificationPoliciesRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + + action := "ListNotificationPolicies" + request := map[string]interface{}{ + "Page": 1, + "Size": PageSizeXLarge, + "RegionId": client.RegionId, + "IsDetail": true, + } + if v, ok := d.GetOk("name"); ok { + request["Name"] = v + } + var objects []map[string]interface{} + var nameRegex *regexp.Regexp + if v, ok := d.GetOk("name_regex"); ok { + r, err := regexp.Compile(v.(string)) + if err != nil { + return WrapError(err) + } + nameRegex = r + } + + idsMap := make(map[string]string) + if v, ok := d.GetOk("ids"); ok { + for _, vv := range v.([]interface{}) { + if vv == nil { + continue + } + idsMap[vv.(string)] = vv.(string) + } + } + var response map[string]interface{} + var err error + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(5*time.Minute, func() *resource.RetryError { + response, err = client.RpcPost("ARMS", "2019-08-08", action, nil, request, true) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_arms_notification_policies", action, AlibabaCloudSdkGoERROR) + } + resp, err := jsonpath.Get("$.PageBean.NotificationPolicies", response) + if err != nil { + return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PageBean.NotificationPolicies", response) + } + result, _ := resp.([]interface{}) + for _, v := range result { + item := v.(map[string]interface{}) + if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Name"])) { + continue + } + if len(idsMap) > 0 { + if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok { + continue + } + } + objects = append(objects, item) + } + ids := make([]string, 0) + names := make([]interface{}, 0) + s := make([]map[string]interface{}, 0) + for _, object := range objects { + mapping := map[string]interface{}{ + "id": fmt.Sprint(object["Id"]), + "name": object["Name"], + "state": object["State"], + } + ids = append(ids, fmt.Sprint(object["Id"])) + names = append(names, object["Name"]) + if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) { + s = append(s, mapping) + continue + } + + mapping["repeat"] = object["Repeat"] + mapping["repeat_interval"] = object["RepeatInterval"] + mapping["send_recover_message"] = object["SendRecoverMessage"] + mapping["escalation_policy_id"] = object["EscalationPolicyId"] + mapping["integration_id"] = object["IntegrationId"] + mapping["directed_mode"] = object["DirectedMode"] + + if groupRule, ok := object["GroupRule"]; ok && groupRule != nil { + if groupRuleObj, ok := groupRule.(map[string]interface{}); ok { + mapping["group_rule"] = []map[string]interface{}{ + { + "group_wait": groupRuleObj["GroupWait"], + "group_interval": groupRuleObj["GroupInterval"], + "grouping_fields": groupRuleObj["GroupingFields"], + }, + } + } + } + + if matchingRules, ok := object["MatchingRules"]; ok && matchingRules != nil { + matchingRulesMaps := make([]map[string]interface{}, 0) + for _, matchingRule := range matchingRules.([]interface{}) { + matchingRuleObj := matchingRule.(map[string]interface{}) + matchingConditionsMaps := make([]map[string]interface{}, 0) + if conditions, ok := matchingRuleObj["MatchingConditions"]; ok && conditions != nil { + for _, condition := range conditions.([]interface{}) { + conditionObj := condition.(map[string]interface{}) + matchingConditionsMaps = append(matchingConditionsMaps, map[string]interface{}{ + "key": conditionObj["Key"], + "value": conditionObj["Value"], + "operator": conditionObj["Operator"], + }) + } + } + matchingRulesMaps = append(matchingRulesMaps, map[string]interface{}{ + "matching_conditions": matchingConditionsMaps, + }) + } + mapping["matching_rules"] = matchingRulesMaps + } + + if notifyRule, ok := object["NotifyRule"]; ok && notifyRule != nil { + if notifyRuleObj, ok := notifyRule.(map[string]interface{}); ok { + notifyObjectsMaps := make([]map[string]interface{}, 0) + if notifyObjects, ok := notifyRuleObj["NotifyObjects"]; ok && notifyObjects != nil { + for _, notifyObject := range notifyObjects.([]interface{}) { + notifyObjectObj := notifyObject.(map[string]interface{}) + notifyObjectMap := map[string]interface{}{ + "notify_object_type": notifyObjectObj["NotifyObjectType"], + "notify_object_id": fmt.Sprint(notifyObjectObj["NotifyObjectId"]), + "notify_object_name": notifyObjectObj["NotifyObjectName"], + } + if v, ok := notifyObjectObj["NotifyChannels"]; ok { + notifyObjectMap["notify_channels"] = v + } + notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectMap) + } + } + mapping["notify_rule"] = []map[string]interface{}{ + { + "notify_start_time": notifyRuleObj["NotifyStartTime"], + "notify_end_time": notifyRuleObj["NotifyEndTime"], + "notify_channels": notifyRuleObj["NotifyChannels"], + "notify_objects": notifyObjectsMaps, + }, + } + } + } + + if notifyTemplate, ok := object["NotifyTemplate"]; ok && notifyTemplate != nil { + if notifyTemplateObj, ok := notifyTemplate.(map[string]interface{}); ok { + mapping["notify_template"] = []map[string]interface{}{ + { + "email_title": notifyTemplateObj["EmailTitle"], + "email_content": notifyTemplateObj["EmailContent"], + "email_recover_title": notifyTemplateObj["EmailRecoverTitle"], + "email_recover_content": notifyTemplateObj["EmailRecoverContent"], + "sms_content": notifyTemplateObj["SmsContent"], + "sms_recover_content": notifyTemplateObj["SmsRecoverContent"], + "tts_content": notifyTemplateObj["TtsContent"], + "tts_recover_content": notifyTemplateObj["TtsRecoverContent"], + "robot_content": notifyTemplateObj["RobotContent"], + }, + } + } + } + + s = append(s, mapping) + } + + d.SetId(dataResourceIdHash(ids)) + if err := d.Set("ids", ids); err != nil { + return WrapError(err) + } + + if err := d.Set("names", names); err != nil { + return WrapError(err) + } + + if err := d.Set("policies", s); err != nil { + return WrapError(err) + } + if output, ok := d.GetOk("output_file"); ok && output.(string) != "" { + writeToFile(output.(string), s) + } + + return nil +} diff --git a/alicloud/data_source_alicloud_arms_notification_policies_test.go b/alicloud/data_source_alicloud_arms_notification_policies_test.go new file mode 100644 index 000000000000..e744a608457e --- /dev/null +++ b/alicloud/data_source_alicloud_arms_notification_policies_test.go @@ -0,0 +1,142 @@ +package alicloud + +import ( + "fmt" + "testing" + + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" +) + +func TestAccAlicloudARMSNotificationPoliciesDataSource(t *testing.T) { + rand := acctest.RandInt() + resourceId := "data.alicloud_arms_notification_policies.default" + name := fmt.Sprintf("tf-testacc-armsNotificationPolicies%v", rand) + + testAccConfig := dataSourceTestAccConfigFunc(resourceId, name, dataSourceArmsNotificationPoliciesConfigDependence) + + nameRegexConf := dataSourceTestAccConfig{ + existConfig: testAccConfig(map[string]interface{}{ + "name_regex": "${alicloud_arms_notification_policy.default.name}", + "enable_details": "true", + }), + fakeConfig: testAccConfig(map[string]interface{}{ + "name_regex": "fake_tf-testacc*", + }), + } + + nameConf := dataSourceTestAccConfig{ + existConfig: testAccConfig(map[string]interface{}{ + "name": "${alicloud_arms_notification_policy.default.name}", + "enable_details": "true", + }), + fakeConfig: testAccConfig(map[string]interface{}{ + "name": "fake_tf-testacc*", + }), + } + + idsConf := dataSourceTestAccConfig{ + existConfig: testAccConfig(map[string]interface{}{ + "ids": []string{"${alicloud_arms_notification_policy.default.id}"}, + "enable_details": "true", + }), + fakeConfig: testAccConfig(map[string]interface{}{ + "ids": []string{"${alicloud_arms_notification_policy.default.id}_fake"}, + }), + } + + allConf := dataSourceTestAccConfig{ + existConfig: testAccConfig(map[string]interface{}{ + "name_regex": "${alicloud_arms_notification_policy.default.name}", + "name": "${alicloud_arms_notification_policy.default.name}", + "ids": []string{"${alicloud_arms_notification_policy.default.id}"}, + "enable_details": "true", + }), + fakeConfig: testAccConfig(map[string]interface{}{ + "name_regex": "${alicloud_arms_notification_policy.default.name}", + "name": "${alicloud_arms_notification_policy.default.name}_fake", + "ids": []string{"${alicloud_arms_notification_policy.default.id}"}, + }), + } + + var existArmsNotificationPoliciesMapFunc = func(rand int) map[string]string { + return map[string]string{ + "ids.#": "1", + "names.#": "1", + "policies.#": "1", + "policies.0.id": CHECKSET, + "policies.0.name": name, + "policies.0.notify_rule.#": "1", + "policies.0.group_rule.#": "1", + } + } + + var fakeArmsNotificationPoliciesMapFunc = func(rand int) map[string]string { + return map[string]string{ + "policies.#": "0", + "names.#": "0", + "ids.#": "0", + } + } + + var ArmsNotificationPoliciesCheckInfo = dataSourceAttr{ + resourceId: resourceId, + existMapFunc: existArmsNotificationPoliciesMapFunc, + fakeMapFunc: fakeArmsNotificationPoliciesMapFunc, + } + preCheck := func() { + testAccPreCheck(t) + testAccPreCheckWithRegions(t, true, connectivity.ARMSSupportRegions) + } + ArmsNotificationPoliciesCheckInfo.dataSourceTestCheckWithPreCheck(t, rand, preCheck, nameRegexConf, nameConf, idsConf, allConf) +} + +func dataSourceArmsNotificationPoliciesConfigDependence(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%v" +} + +resource "alicloud_arms_alert_contact" "default" { + alert_contact_name = var.name + email = "${var.name}@aaa.com" +} + +resource "alicloud_arms_alert_contact_group" "default" { + alert_contact_group_name = var.name + contact_ids = [alicloud_arms_alert_contact.default.id] +} + +resource "alicloud_arms_notification_policy" "default" { + name = var.name + + group_rule { + group_wait = 5 + group_interval = 30 + grouping_fields = ["alertname"] + } + + matching_rules { + matching_conditions { + key = "_aliyun_arms_involvedObject_kind" + value = "app" + operator = "eq" + } + } + + notify_rule { + notify_start_time = "00:00" + notify_end_time = "23:59" + notify_channels = ["dingTalk", "email"] + notify_objects { + notify_object_type = "ARMS_CONTACT" + notify_object_id = alicloud_arms_alert_contact.default.id + notify_object_name = var.name + } + } + + repeat = true + repeat_interval = 600 +} +`, name) +} diff --git a/alicloud/provider.go b/alicloud/provider.go index a3c2f5d1540c..f350516ce52e 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -619,6 +619,7 @@ func Provider() terraform.ResourceProvider { "alicloud_quick_bi_users": dataSourceAlicloudQuickBiUsers(), "alicloud_vod_domains": dataSourceAlicloudVodDomains(), "alicloud_arms_dispatch_rules": dataSourceAlicloudArmsDispatchRules(), + "alicloud_arms_notification_policies": dataSourceAlicloudArmsNotificationPolicies(), "alicloud_open_search_app_groups": dataSourceAlicloudOpenSearchAppGroups(), "alicloud_graph_database_db_instances": dataSourceAlicloudGraphDatabaseDbInstances(), "alicloud_arms_prometheus_alert_rules": dataSourceAlicloudArmsPrometheusAlertRules(), @@ -1738,6 +1739,7 @@ func Provider() terraform.ResourceProvider { "alicloud_quick_bi_user": resourceAlicloudQuickBiUser(), "alicloud_vod_domain": resourceAlicloudVodDomain(), "alicloud_arms_dispatch_rule": resourceAlicloudArmsDispatchRule(), + "alicloud_arms_notification_policy": resourceAlicloudArmsNotificationPolicy(), "alicloud_open_search_app_group": resourceAlicloudOpenSearchAppGroup(), "alicloud_graph_database_db_instance": resourceAlicloudGraphDatabaseDbInstance(), "alicloud_arms_prometheus_alert_rule": resourceAlicloudArmsPrometheusAlertRule(), diff --git a/alicloud/resource_alicloud_arms_notification_policy.go b/alicloud/resource_alicloud_arms_notification_policy.go new file mode 100644 index 000000000000..f591db08cd0b --- /dev/null +++ b/alicloud/resource_alicloud_arms_notification_policy.go @@ -0,0 +1,652 @@ +package alicloud + +import ( + "fmt" + "log" + "time" + + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +) + +func resourceAlicloudArmsNotificationPolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceAlicloudArmsNotificationPolicyCreate, + Read: resourceAlicloudArmsNotificationPolicyRead, + Update: resourceAlicloudArmsNotificationPolicyUpdate, + Delete: resourceAlicloudArmsNotificationPolicyDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "group_rule": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "group_wait": { + Type: schema.TypeInt, + Optional: true, + Default: 5, + }, + "group_interval": { + Type: schema.TypeInt, + Optional: true, + Default: 30, + }, + "grouping_fields": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + "matching_rules": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "matching_conditions": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + }, + "value": { + Type: schema.TypeString, + Required: true, + }, + "operator": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"eq", "neq", "in", "nin", "re", "nre"}, false), + }, + }, + }, + }, + }, + }, + }, + "notify_rule": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "notify_start_time": { + Type: schema.TypeString, + Required: true, + }, + "notify_end_time": { + Type: schema.TypeString, + Required: true, + }, + "notify_channels": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "notify_objects": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "notify_object_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"CONTACT", "CONTACT_GROUP", "ARMS_CONTACT", "ARMS_CONTACT_GROUP", "DING_ROBOT_GROUP", "CONTACT_SCHEDULE"}, false), + }, + "notify_object_id": { + Type: schema.TypeString, + Required: true, + }, + "notify_object_name": { + Type: schema.TypeString, + Required: true, + }, + "notify_channels": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + }, + }, + }, + "notify_template": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "email_title": { + Type: schema.TypeString, + Optional: true, + }, + "email_content": { + Type: schema.TypeString, + Optional: true, + }, + "email_recover_title": { + Type: schema.TypeString, + Optional: true, + }, + "email_recover_content": { + Type: schema.TypeString, + Optional: true, + }, + "sms_content": { + Type: schema.TypeString, + Optional: true, + }, + "sms_recover_content": { + Type: schema.TypeString, + Optional: true, + }, + "tts_content": { + Type: schema.TypeString, + Optional: true, + }, + "tts_recover_content": { + Type: schema.TypeString, + Optional: true, + }, + "robot_content": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "escalation_policy_id": { + Type: schema.TypeInt, + Optional: true, + }, + "integration_id": { + Type: schema.TypeInt, + Optional: true, + }, + "repeat": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "repeat_interval": { + Type: schema.TypeInt, + Optional: true, + }, + "send_recover_message": { + Type: schema.TypeBool, + Optional: true, + }, + "state": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"enable", "disable"}, false), + }, + "directed_mode": { + Type: schema.TypeBool, + Optional: true, + }, + }, + } +} + +func resourceAlicloudArmsNotificationPolicyCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + var response map[string]interface{} + action := "CreateOrUpdateNotificationPolicy" + request := make(map[string]interface{}) + var err error + + request["RegionId"] = client.RegionId + request["Name"] = d.Get("name") + + if v, ok := d.GetOk("group_rule"); ok { + groupRuleList := v.([]interface{}) + if len(groupRuleList) > 0 { + groupRuleArg := groupRuleList[0].(map[string]interface{}) + groupRuleMap := map[string]interface{}{ + "groupWait": groupRuleArg["group_wait"], + "groupInterval": groupRuleArg["group_interval"], + } + if v, ok := groupRuleArg["grouping_fields"]; ok { + groupRuleMap["groupingFields"] = v + } + if jsonStr, err := convertMaptoJsonString(groupRuleMap); err != nil { + return WrapError(err) + } else { + request["GroupRule"] = jsonStr + } + } + } + + if v, ok := d.GetOk("matching_rules"); ok { + matchingRulesList := v.([]interface{}) + matchingRulesMaps := make([]map[string]interface{}, 0) + for _, matchingRules := range matchingRulesList { + matchingRulesArg := matchingRules.(map[string]interface{}) + matchingConditionsMaps := make([]map[string]interface{}, 0) + for _, condition := range matchingRulesArg["matching_conditions"].([]interface{}) { + conditionArg := condition.(map[string]interface{}) + matchingConditionsMaps = append(matchingConditionsMaps, map[string]interface{}{ + "key": conditionArg["key"], + "value": conditionArg["value"], + "operator": conditionArg["operator"], + }) + } + matchingRulesMaps = append(matchingRulesMaps, map[string]interface{}{ + "matchingConditions": matchingConditionsMaps, + }) + } + if jsonStr, err := convertListMapToJsonString(matchingRulesMaps); err != nil { + return WrapError(err) + } else { + request["MatchingRules"] = jsonStr + } + } + + if v, ok := d.GetOk("notify_rule"); ok { + notifyRuleList := v.([]interface{}) + if len(notifyRuleList) > 0 { + notifyRuleArg := notifyRuleList[0].(map[string]interface{}) + notifyObjectsMaps := make([]map[string]interface{}, 0) + for _, notifyObject := range notifyRuleArg["notify_objects"].([]interface{}) { + notifyObjectArg := notifyObject.(map[string]interface{}) + notifyObjectMap := map[string]interface{}{ + "notifyObjectType": notifyObjectArg["notify_object_type"], + "notifyObjectId": notifyObjectArg["notify_object_id"], + "notifyObjectName": notifyObjectArg["notify_object_name"], + } + if v, ok := notifyObjectArg["notify_channels"]; ok { + notifyObjectMap["notifyChannels"] = v + } + notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectMap) + } + notifyRuleMap := map[string]interface{}{ + "notifyStartTime": notifyRuleArg["notify_start_time"], + "notifyEndTime": notifyRuleArg["notify_end_time"], + "notifyChannels": notifyRuleArg["notify_channels"], + "notifyObjects": notifyObjectsMaps, + } + if jsonStr, err := convertMaptoJsonString(notifyRuleMap); err != nil { + return WrapError(err) + } else { + request["NotifyRule"] = jsonStr + } + } + } + + if v, ok := d.GetOk("notify_template"); ok { + notifyTemplateList := v.([]interface{}) + if len(notifyTemplateList) > 0 { + notifyTemplateArg := notifyTemplateList[0].(map[string]interface{}) + notifyTemplateMap := map[string]interface{}{ + "emailTitle": notifyTemplateArg["email_title"], + "emailContent": notifyTemplateArg["email_content"], + "emailRecoverTitle": notifyTemplateArg["email_recover_title"], + "emailRecoverContent": notifyTemplateArg["email_recover_content"], + "smsContent": notifyTemplateArg["sms_content"], + "smsRecoverContent": notifyTemplateArg["sms_recover_content"], + "ttsContent": notifyTemplateArg["tts_content"], + "ttsRecoverContent": notifyTemplateArg["tts_recover_content"], + "robotContent": notifyTemplateArg["robot_content"], + } + if jsonStr, err := convertMaptoJsonString(notifyTemplateMap); err != nil { + return WrapError(err) + } else { + request["NotifyTemplate"] = jsonStr + } + } + } + + if v, ok := d.GetOk("escalation_policy_id"); ok { + request["EscalationPolicyId"] = v + } + if v, ok := d.GetOk("integration_id"); ok { + request["IntegrationId"] = v + } + if v, ok := d.GetOkExists("repeat"); ok { + request["Repeat"] = v + } + if v, ok := d.GetOk("repeat_interval"); ok { + request["RepeatInterval"] = v + } + if v, ok := d.GetOkExists("send_recover_message"); ok { + request["SendRecoverMessage"] = v + } + if v, ok := d.GetOk("state"); ok { + request["State"] = v + } + if v, ok := d.GetOkExists("directed_mode"); ok { + request["DirectedMode"] = v + } + + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { + response, err = client.RpcPost("ARMS", "2019-08-08", action, nil, request, false) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, "alicloud_arms_notification_policy", action, AlibabaCloudSdkGoERROR) + } + + notificationPolicy, ok := response["NotificationPolicy"].(map[string]interface{}) + if !ok { + return WrapErrorf(fmt.Errorf("NotificationPolicy is not valid"), DefaultErrorMsg, "alicloud_arms_notification_policy", action, AlibabaCloudSdkGoERROR) + } + d.SetId(fmt.Sprint(notificationPolicy["Id"])) + + return resourceAlicloudArmsNotificationPolicyRead(d, meta) +} + +func resourceAlicloudArmsNotificationPolicyRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + armsService := ArmsService{client} + object, err := armsService.ListArmsNotificationPolicies(d.Id()) + if err != nil { + if NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_arms_notification_policy armsService.ListArmsNotificationPolicies Failed!!! %s", err) + d.SetId("") + return nil + } + return WrapError(err) + } + + d.Set("name", object["Name"]) + d.Set("state", object["State"]) + d.Set("directed_mode", object["DirectedMode"]) + d.Set("escalation_policy_id", object["EscalationPolicyId"]) + d.Set("integration_id", object["IntegrationId"]) + d.Set("repeat", object["Repeat"]) + d.Set("repeat_interval", object["RepeatInterval"]) + d.Set("send_recover_message", object["SendRecoverMessage"]) + + if groupRule, ok := object["GroupRule"]; ok && groupRule != nil { + groupRuleObj := groupRule.(map[string]interface{}) + if len(groupRuleObj) > 0 { + groupRuleMaps := []map[string]interface{}{ + { + "group_wait": groupRuleObj["GroupWait"], + "group_interval": groupRuleObj["GroupInterval"], + "grouping_fields": groupRuleObj["GroupingFields"], + }, + } + d.Set("group_rule", groupRuleMaps) + } + } + + if matchingRules, ok := object["MatchingRules"]; ok && matchingRules != nil { + matchingRulesList := matchingRules.([]interface{}) + matchingRulesMaps := make([]map[string]interface{}, 0) + for _, matchingRule := range matchingRulesList { + matchingRuleObj := matchingRule.(map[string]interface{}) + matchingConditionsMaps := make([]map[string]interface{}, 0) + if conditions, ok := matchingRuleObj["MatchingConditions"]; ok && conditions != nil { + for _, condition := range conditions.([]interface{}) { + conditionObj := condition.(map[string]interface{}) + matchingConditionsMaps = append(matchingConditionsMaps, map[string]interface{}{ + "key": conditionObj["Key"], + "value": conditionObj["Value"], + "operator": conditionObj["Operator"], + }) + } + } + matchingRulesMaps = append(matchingRulesMaps, map[string]interface{}{ + "matching_conditions": matchingConditionsMaps, + }) + } + d.Set("matching_rules", matchingRulesMaps) + } + + if notifyRule, ok := object["NotifyRule"]; ok && notifyRule != nil { + notifyRuleObj := notifyRule.(map[string]interface{}) + notifyObjectsMaps := make([]map[string]interface{}, 0) + if notifyObjects, ok := notifyRuleObj["NotifyObjects"]; ok && notifyObjects != nil { + for _, notifyObject := range notifyObjects.([]interface{}) { + notifyObjectObj := notifyObject.(map[string]interface{}) + notifyObjectMap := map[string]interface{}{ + "notify_object_type": notifyObjectObj["NotifyObjectType"], + "notify_object_id": fmt.Sprint(notifyObjectObj["NotifyObjectId"]), + "notify_object_name": notifyObjectObj["NotifyObjectName"], + } + if v, ok := notifyObjectObj["NotifyChannels"]; ok { + notifyObjectMap["notify_channels"] = v + } + notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectMap) + } + } + notifyRuleMaps := []map[string]interface{}{ + { + "notify_start_time": notifyRuleObj["NotifyStartTime"], + "notify_end_time": notifyRuleObj["NotifyEndTime"], + "notify_channels": notifyRuleObj["NotifyChannels"], + "notify_objects": notifyObjectsMaps, + }, + } + d.Set("notify_rule", notifyRuleMaps) + } + + if notifyTemplate, ok := object["NotifyTemplate"]; ok && notifyTemplate != nil { + notifyTemplateObj := notifyTemplate.(map[string]interface{}) + if len(notifyTemplateObj) > 0 { + notifyTemplateMaps := []map[string]interface{}{ + { + "email_title": notifyTemplateObj["EmailTitle"], + "email_content": notifyTemplateObj["EmailContent"], + "email_recover_title": notifyTemplateObj["EmailRecoverTitle"], + "email_recover_content": notifyTemplateObj["EmailRecoverContent"], + "sms_content": notifyTemplateObj["SmsContent"], + "sms_recover_content": notifyTemplateObj["SmsRecoverContent"], + "tts_content": notifyTemplateObj["TtsContent"], + "tts_recover_content": notifyTemplateObj["TtsRecoverContent"], + "robot_content": notifyTemplateObj["RobotContent"], + }, + } + d.Set("notify_template", notifyTemplateMaps) + } + } + + return nil +} + +func resourceAlicloudArmsNotificationPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + var response map[string]interface{} + action := "CreateOrUpdateNotificationPolicy" + request := make(map[string]interface{}) + var err error + + request["RegionId"] = client.RegionId + request["Id"] = d.Id() + request["Name"] = d.Get("name") + + if v, ok := d.GetOk("group_rule"); ok { + groupRuleList := v.([]interface{}) + if len(groupRuleList) > 0 { + groupRuleArg := groupRuleList[0].(map[string]interface{}) + groupRuleMap := map[string]interface{}{ + "groupWait": groupRuleArg["group_wait"], + "groupInterval": groupRuleArg["group_interval"], + } + if v, ok := groupRuleArg["grouping_fields"]; ok { + groupRuleMap["groupingFields"] = v + } + if jsonStr, err := convertMaptoJsonString(groupRuleMap); err != nil { + return WrapError(err) + } else { + request["GroupRule"] = jsonStr + } + } + } + + if v, ok := d.GetOk("matching_rules"); ok { + matchingRulesList := v.([]interface{}) + matchingRulesMaps := make([]map[string]interface{}, 0) + for _, matchingRules := range matchingRulesList { + matchingRulesArg := matchingRules.(map[string]interface{}) + matchingConditionsMaps := make([]map[string]interface{}, 0) + for _, condition := range matchingRulesArg["matching_conditions"].([]interface{}) { + conditionArg := condition.(map[string]interface{}) + matchingConditionsMaps = append(matchingConditionsMaps, map[string]interface{}{ + "key": conditionArg["key"], + "value": conditionArg["value"], + "operator": conditionArg["operator"], + }) + } + matchingRulesMaps = append(matchingRulesMaps, map[string]interface{}{ + "matchingConditions": matchingConditionsMaps, + }) + } + if jsonStr, err := convertListMapToJsonString(matchingRulesMaps); err != nil { + return WrapError(err) + } else { + request["MatchingRules"] = jsonStr + } + } + + if v, ok := d.GetOk("notify_rule"); ok { + notifyRuleList := v.([]interface{}) + if len(notifyRuleList) > 0 { + notifyRuleArg := notifyRuleList[0].(map[string]interface{}) + notifyObjectsMaps := make([]map[string]interface{}, 0) + for _, notifyObject := range notifyRuleArg["notify_objects"].([]interface{}) { + notifyObjectArg := notifyObject.(map[string]interface{}) + notifyObjectMap := map[string]interface{}{ + "notifyObjectType": notifyObjectArg["notify_object_type"], + "notifyObjectId": notifyObjectArg["notify_object_id"], + "notifyObjectName": notifyObjectArg["notify_object_name"], + } + if v, ok := notifyObjectArg["notify_channels"]; ok { + notifyObjectMap["notifyChannels"] = v + } + notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectMap) + } + notifyRuleMap := map[string]interface{}{ + "notifyStartTime": notifyRuleArg["notify_start_time"], + "notifyEndTime": notifyRuleArg["notify_end_time"], + "notifyChannels": notifyRuleArg["notify_channels"], + "notifyObjects": notifyObjectsMaps, + } + if jsonStr, err := convertMaptoJsonString(notifyRuleMap); err != nil { + return WrapError(err) + } else { + request["NotifyRule"] = jsonStr + } + } + } + + if v, ok := d.GetOk("notify_template"); ok { + notifyTemplateList := v.([]interface{}) + if len(notifyTemplateList) > 0 { + notifyTemplateArg := notifyTemplateList[0].(map[string]interface{}) + notifyTemplateMap := map[string]interface{}{ + "emailTitle": notifyTemplateArg["email_title"], + "emailContent": notifyTemplateArg["email_content"], + "emailRecoverTitle": notifyTemplateArg["email_recover_title"], + "emailRecoverContent": notifyTemplateArg["email_recover_content"], + "smsContent": notifyTemplateArg["sms_content"], + "smsRecoverContent": notifyTemplateArg["sms_recover_content"], + "ttsContent": notifyTemplateArg["tts_content"], + "ttsRecoverContent": notifyTemplateArg["tts_recover_content"], + "robotContent": notifyTemplateArg["robot_content"], + } + if jsonStr, err := convertMaptoJsonString(notifyTemplateMap); err != nil { + return WrapError(err) + } else { + request["NotifyTemplate"] = jsonStr + } + } + } + + if v, ok := d.GetOk("escalation_policy_id"); ok { + request["EscalationPolicyId"] = v + } + if v, ok := d.GetOk("integration_id"); ok { + request["IntegrationId"] = v + } + if v, ok := d.GetOkExists("repeat"); ok { + request["Repeat"] = v + } + if v, ok := d.GetOk("repeat_interval"); ok { + request["RepeatInterval"] = v + } + if v, ok := d.GetOkExists("send_recover_message"); ok { + request["SendRecoverMessage"] = v + } + if v, ok := d.GetOk("state"); ok { + request["State"] = v + } + if v, ok := d.GetOkExists("directed_mode"); ok { + request["DirectedMode"] = v + } + + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = client.RpcPost("ARMS", "2019-08-08", action, nil, request, false) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + return resourceAlicloudArmsNotificationPolicyRead(d, meta) +} + +func resourceAlicloudArmsNotificationPolicyDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + action := "DeleteNotificationPolicy" + var response map[string]interface{} + var err error + request := map[string]interface{}{ + "Id": d.Id(), + "RegionId": client.RegionId, + } + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { + response, err = client.RpcPost("ARMS", "2019-08-08", action, nil, request, false) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + return nil +} diff --git a/alicloud/resource_alicloud_arms_notification_policy_test.go b/alicloud/resource_alicloud_arms_notification_policy_test.go new file mode 100644 index 000000000000..b5f0c5333d4e --- /dev/null +++ b/alicloud/resource_alicloud_arms_notification_policy_test.go @@ -0,0 +1,320 @@ +package alicloud + +import ( + "fmt" + "log" + "strings" + "testing" + "time" + + "github.com/PaesslerAG/jsonpath" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func init() { + resource.AddTestSweepers("alicloud_arms_notification_policy", &resource.Sweeper{ + Name: "alicloud_arms_notification_policy", + F: testSweepArmsNotificationPolicy, + }) +} + +func testSweepArmsNotificationPolicy(region string) error { + rawClient, err := sharedClientForRegion(region) + if err != nil { + return WrapErrorf(err, "error getting Alicloud client.") + } + client := rawClient.(*connectivity.AliyunClient) + + prefixes := []string{ + "tf-testAcc", + "tf_testacc", + } + + action := "ListNotificationPolicies" + request := map[string]interface{}{ + "RegionId": client.RegionId, + "Page": 1, + "Size": PageSizeXLarge, + } + var response map[string]interface{} + wait := incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(2*time.Minute, func() *resource.RetryError { + response, err = client.RpcPost("ARMS", "2019-08-08", action, nil, request, true) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + log.Printf("[ERROR] %s failed: %v", action, err) + return nil + } + resp, err := jsonpath.Get("$.PageBean.NotificationPolicies", response) + if err != nil { + log.Printf("[ERROR] %v", WrapError(err)) + return nil + } + result, _ := resp.([]interface{}) + for _, v := range result { + item := v.(map[string]interface{}) + name := fmt.Sprint(item["Name"]) + skip := true + if !sweepAll() { + for _, prefix := range prefixes { + if strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) { + skip = false + break + } + } + if skip { + log.Printf("[INFO] Skipping notification policy: %s ", name) + continue + } + } + log.Printf("[INFO] delete notification policy: %s ", name) + + action = "DeleteNotificationPolicy" + request = map[string]interface{}{ + "Id": fmt.Sprint(item["Id"]), + "RegionId": client.RegionId, + } + wait = incrementalWait(3*time.Second, 3*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = client.RpcPost("ARMS", "2019-08-08", action, nil, request, false) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + log.Printf("[ERROR] %s failed: %v", action, err) + } + } + return nil +} + +func TestAccAliCloudARMSNotificationPolicy_basic(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_arms_notification_policy.default" + ra := resourceAttrInit(resourceId, ArmsNotificationPolicyMap) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &ArmsService{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "ListArmsNotificationPolicies") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(1000000, 9999999) + name := fmt.Sprintf("tf-testAccArmsNotificationPolicy%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, ArmsNotificationPolicyBasicdependence) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccPreCheckWithRegions(t, true, connectivity.ARMSSupportRegions) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "name": "${var.name}", + "notify_rule": []map[string]interface{}{ + { + "notify_start_time": "00:00", + "notify_end_time": "23:59", + "notify_channels": []string{"dingTalk", "email"}, + "notify_objects": []map[string]interface{}{ + { + "notify_object_type": "ARMS_CONTACT", + "notify_object_id": "${alicloud_arms_alert_contact.default.id}", + "notify_object_name": "${var.name}", + }, + }, + }, + }, + "group_rule": []map[string]interface{}{ + { + "group_wait": "5", + "group_interval": "30", + "grouping_fields": []string{"alertname"}, + }, + }, + "matching_rules": []map[string]interface{}{ + { + "matching_conditions": []map[string]interface{}{ + { + "key": "_aliyun_arms_involvedObject_kind", + "value": "app", + "operator": "eq", + }, + }, + }, + }, + "repeat": "true", + "repeat_interval": "600", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "name": CHECKSET, + "notify_rule.#": "1", + "group_rule.#": "1", + "matching_rules.#": "1", + "repeat": "true", + "repeat_interval": "600", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "name": "${var.name}_update", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "name": name + "_update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "notify_rule": []map[string]interface{}{ + { + "notify_start_time": "01:00", + "notify_end_time": "22:00", + "notify_channels": []string{"dingTalk"}, + "notify_objects": []map[string]interface{}{ + { + "notify_object_type": "ARMS_CONTACT", + "notify_object_id": "${alicloud_arms_alert_contact.default.id}", + "notify_object_name": "${var.name}", + }, + { + "notify_object_type": "ARMS_CONTACT_GROUP", + "notify_object_id": "${alicloud_arms_alert_contact_group.default.id}", + "notify_object_name": "${var.name}", + }, + }, + }, + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "notify_rule.#": "1", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "repeat_interval": "300", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_interval": "300", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "notify_template": []map[string]interface{}{ + { + "email_title": "CreateEmailTitle", + "email_content": "CreateEmailContent", + "email_recover_title": "CreateEmailRecoverTitle", + "email_recover_content": "CreateEmailRecoverContent", + "sms_content": "CreateSmsContent", + "sms_recover_content": "CreateSmsRecoverContent", + "tts_content": "CreateTtsContent", + "tts_recover_content": "CreateTtsRecoverContent", + "robot_content": "CreateRobotContent", + }, + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "notify_template.#": "1", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "send_recover_message": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "send_recover_message": "true", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "name": "${var.name}", + "notify_rule": []map[string]interface{}{ + { + "notify_start_time": "00:00", + "notify_end_time": "23:59", + "notify_channels": []string{"dingTalk", "email"}, + "notify_objects": []map[string]interface{}{ + { + "notify_object_type": "ARMS_CONTACT", + "notify_object_id": "${alicloud_arms_alert_contact.default.id}", + "notify_object_name": "${var.name}", + }, + }, + }, + }, + "group_rule": []map[string]interface{}{ + { + "group_wait": "5", + "group_interval": "30", + "grouping_fields": []string{"alertname"}, + }, + }, + "repeat": "true", + "repeat_interval": "600", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "name": CHECKSET, + "notify_rule.#": "1", + "group_rule.#": "1", + "repeat": "true", + "repeat_interval": "600", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +var ArmsNotificationPolicyMap = map[string]string{} + +func ArmsNotificationPolicyBasicdependence(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} +resource "alicloud_arms_alert_contact" "default" { + alert_contact_name = "${var.name}" + email = "${var.name}@aaa.com" +} +resource "alicloud_arms_alert_contact_group" "default" { + alert_contact_group_name = "${var.name}" + contact_ids = [alicloud_arms_alert_contact.default.id] +} +`, name) +} diff --git a/website/docs/d/arms_notification_policies.html.markdown b/website/docs/d/arms_notification_policies.html.markdown new file mode 100644 index 000000000000..6fa58faf299c --- /dev/null +++ b/website/docs/d/arms_notification_policies.html.markdown @@ -0,0 +1,91 @@ +--- +subcategory: "Application Real-Time Monitoring Service (ARMS)" +layout: "alicloud" +page_title: "Alicloud: alicloud_arms_notification_policies" +sidebar_current: "docs-alicloud-datasource-arms-notification-policies" +description: |- + Provides a list of Alicloud Application Real-Time Monitoring Service (ARMS) Notification Policies. +--- + +# alicloud_arms_notification_policies + +This data source provides the ARMS Notification Policies of the current Alibaba Cloud user. + +For information about Application Real-Time Monitoring Service (ARMS) Notification Policy and how to use it, see [What is Notification Policy](https://next.api.alibabacloud.com/document/ARMS/2019-08-08/CreateOrUpdateNotificationPolicy). + +## Example Usage + +Basic Usage + +```terraform +data "alicloud_arms_notification_policies" "ids" { + ids = ["example_id"] +} + +output "arms_notification_policies_id_0" { + value = data.alicloud_arms_notification_policies.ids.policies.0.id +} + +data "alicloud_arms_notification_policies" "nameRegex" { + name_regex = "^my-NotificationPolicy" +} + +output "arms_notification_policies_name_regex_0" { + value = data.alicloud_arms_notification_policies.nameRegex.policies.0.id +} +``` + +## Argument Reference + +The following arguments are supported: + +* `ids` - (Optional) A list of Notification Policy IDs. +* `name_regex` - (Optional) A regex string to filter results by Notification Policy name. +* `name` - (Optional) The name of the notification policy. +* `enable_details` - (Optional, Bool) Default to `false`. Set it to `true` to output more details about the resource. +* `output_file` - (Optional) File name where to save data source results (after running `terraform plan`). + +## Attributes Reference + +The following attributes are exported in addition to the arguments listed above: + +* `ids` - A list of Notification Policy IDs. +* `names` - A list of Notification Policy names. +* `policies` - A list of ARMS Notification Policies. Each element contains the following attributes: + * `id` - The ID of the Notification Policy. + * `name` - The name of the Notification Policy. + * `state` - The state of the Notification Policy. Valid values: `enable`, `disable`. + * `repeat` - Whether to resend notifications for long-lasting unresolved alerts. + * `repeat_interval` - The time interval (in seconds) for resending notifications for unresolved alerts. + * `send_recover_message` - Whether to send a notification when the alert is auto-resolved. + * `escalation_policy_id` - The ID of the escalation policy. + * `integration_id` - The integration ID of the ticket system. + * `directed_mode` - Whether simple mode is enabled. + * `group_rule` - The alert event grouping rule. + * `group_wait` - The duration (in seconds) for which the system waits after the first alert is sent. + * `group_interval` - The duration (in seconds) for which the system waits before sending notifications for new alerts in the same group. + * `grouping_fields` - The fields that are used to group events. + * `matching_rules` - The matching rules for the notification policy. + * `matching_conditions` - The matching conditions. + * `key` - The key of the matching condition. + * `value` - The value of the matching condition. + * `operator` - The operator used in the matching condition. + * `notify_rule` - The notification rule. + * `notify_start_time` - The start time of the notification window. + * `notify_end_time` - The end time of the notification window. + * `notify_channels` - The notification channels. + * `notify_objects` - The notification objects. + * `notify_object_type` - The type of the notification object. + * `notify_object_id` - The ID of the notification object. + * `notify_object_name` - The name of the notification object. + * `notify_channels` - The notification channels for this specific object. + * `notify_template` - The notification template. + * `email_title` - The title of the email notification. + * `email_content` - The content of the email notification. + * `email_recover_title` - The title of the email notification for restored alerts. + * `email_recover_content` - The content of the email notification for restored alerts. + * `sms_content` - The content of the SMS notification. + * `sms_recover_content` - The content of the SMS notification for restored alerts. + * `tts_content` - The content of the TTS notification. + * `tts_recover_content` - The content of the TTS notification for restored alerts. + * `robot_content` - The content of the robot notification. diff --git a/website/docs/r/arms_notification_policy.html.markdown b/website/docs/r/arms_notification_policy.html.markdown new file mode 100644 index 000000000000..1bfc71f6a2f3 --- /dev/null +++ b/website/docs/r/arms_notification_policy.html.markdown @@ -0,0 +1,165 @@ +--- +subcategory: "Application Real-Time Monitoring Service (ARMS)" +layout: "alicloud" +page_title: "Alicloud: alicloud_arms_notification_policy" +sidebar_current: "docs-alicloud-resource-arms-notification-policy" +description: |- + Provides a Alicloud Application Real-Time Monitoring Service (ARMS) Notification Policy resource. +--- + +# alicloud_arms_notification_policy + +Provides a Application Real-Time Monitoring Service (ARMS) Notification Policy resource. + +For information about Application Real-Time Monitoring Service (ARMS) Notification Policy and how to use it, see [What is Notification Policy](https://next.api.alibabacloud.com/document/ARMS/2019-08-08/CreateOrUpdateNotificationPolicy). + +## Example Usage + +Basic Usage + +```terraform +resource "alicloud_arms_alert_contact" "default" { + alert_contact_name = "example_value" + email = "example_value@aaa.com" +} + +resource "alicloud_arms_alert_contact_group" "default" { + alert_contact_group_name = "example_value" + contact_ids = [alicloud_arms_alert_contact.default.id] +} + +resource "alicloud_arms_notification_policy" "default" { + name = "example_value" + + group_rule { + group_wait = 5 + group_interval = 30 + grouping_fields = ["alertname"] + } + + matching_rules { + matching_conditions { + key = "_aliyun_arms_involvedObject_kind" + value = "app" + operator = "eq" + } + } + + notify_rule { + notify_start_time = "00:00" + notify_end_time = "23:59" + notify_channels = ["dingTalk", "email"] + notify_objects { + notify_object_type = "ARMS_CONTACT" + notify_object_id = alicloud_arms_alert_contact.default.id + notify_object_name = "example_value" + } + notify_objects { + notify_object_type = "ARMS_CONTACT_GROUP" + notify_object_id = alicloud_arms_alert_contact_group.default.id + notify_object_name = "example_value" + } + } + + notify_template { + email_title = "example_email_title" + email_content = "example_email_content" + email_recover_title = "example_email_recover_title" + email_recover_content = "example_email_recover_content" + sms_content = "example_sms_content" + sms_recover_content = "example_sms_recover_content" + tts_content = "example_tts_content" + tts_recover_content = "example_tts_recover_content" + robot_content = "example_robot_content" + } + + repeat = true + repeat_interval = 600 + send_recover_message = true +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the notification policy. +* `notify_rule` - (Required) The notification rule. See [`notify_rule`](#notify_rule) below. +* `group_rule` - (Optional) The alert event grouping rule. See [`group_rule`](#group_rule) below. +* `matching_rules` - (Optional) The matching rules for the notification policy. See [`matching_rules`](#matching_rules) below. +* `notify_template` - (Optional) The notification template. See [`notify_template`](#notify_template) below. +* `escalation_policy_id` - (Optional) The ID of the escalation policy. +* `integration_id` - (Optional) The integration ID of the ticket system to which alerts are pushed. +* `repeat` - (Optional) Specifies whether to resend notifications for long-lasting unresolved alerts. Default value: `true`. +* `repeat_interval` - (Optional) The time interval (in seconds) for resending notifications for unresolved alerts. +* `send_recover_message` - (Optional) Specifies whether to send a notification when the alert is auto-resolved. +* `state` - (Optional) Specifies whether to enable the notification policy. Valid values: `enable`, `disable`. +* `directed_mode` - (Optional) Specifies whether to enable simple mode. + +### `group_rule` + +The group_rule supports the following: + +* `group_wait` - (Optional) The duration (in seconds) for which the system waits after the first alert is sent. Default value: `5`. +* `group_interval` - (Optional) The duration (in seconds) for which the system waits before sending notifications for new alerts in the same group. Default value: `30`. +* `grouping_fields` - (Optional, List) The fields that are used to group events. Events with the same field content are assigned to a group. + +### `matching_rules` + +The matching_rules supports the following: + +* `matching_conditions` - (Required) The matching conditions. See [`matching_conditions`](#matching_rules-matching_conditions) below. + +### `matching_rules-matching_conditions` + +The matching_conditions supports the following: + +* `key` - (Required) The key of the matching condition. +* `value` - (Required) The value of the matching condition. +* `operator` - (Required) The operator used in the matching condition. Valid values: `eq`, `neq`, `in`, `nin`, `re`, `nre`. + +### `notify_rule` + +The notify_rule supports the following: + +* `notify_start_time` - (Required) The start time of the notification window. Format: `HH:mm`. +* `notify_end_time` - (Required) The end time of the notification window. Format: `HH:mm`. +* `notify_channels` - (Required, List) The notification channels. Valid values: `dingTalk`, `sms`, `webhook`, `email`, `wechat`. +* `notify_objects` - (Required) The notification objects. See [`notify_objects`](#notify_rule-notify_objects) below. + +### `notify_rule-notify_objects` + +The notify_objects supports the following: + +* `notify_object_type` - (Required) The type of the notification object. Valid values: `CONTACT`, `CONTACT_GROUP`, `ARMS_CONTACT`, `ARMS_CONTACT_GROUP`, `DING_ROBOT_GROUP`, `CONTACT_SCHEDULE`. +* `notify_object_id` - (Required) The ID of the notification object. +* `notify_object_name` - (Required) The name of the notification object. +* `notify_channels` - (Optional, List) The notification channels for this specific object. + +### `notify_template` + +The notify_template supports the following: + +* `email_title` - (Optional) The title of the email notification. +* `email_content` - (Optional) The content of the email notification. +* `email_recover_title` - (Optional) The title of the email notification for restored alerts. +* `email_recover_content` - (Optional) The content of the email notification for restored alerts. +* `sms_content` - (Optional) The content of the SMS notification. +* `sms_recover_content` - (Optional) The content of the SMS notification for restored alerts. +* `tts_content` - (Optional) The content of the TTS notification. +* `tts_recover_content` - (Optional) The content of the TTS notification for restored alerts. +* `robot_content` - (Optional) The content of the robot notification. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The resource ID of the Notification Policy. + +## Import + +Application Real-Time Monitoring Service (ARMS) Notification Policy can be imported using the id, e.g. + +```shell +$ terraform import alicloud_arms_notification_policy.example +```