如何通过Terraform在Datadog监控中添加自定义消息变量?
实现Datadog监控消息的自定义内容添加
步骤1:添加自定义消息变量
先在你的变量定义文件(比如variables.tf)里,给aurora_postgres_cpu_utilization这个变量对象新增一个custom_message字段,让用户可以传入自定义内容:
variable "aurora_postgres_cpu_utilization" { type = object({ deploy = bool query_time = string critical_threshold = number warning_threshold = number priority_level = number restricted_roles = list(string) # 新增自定义消息字段,可选,默认空字符串 custom_message = optional(string, "") }) description = "Aurora PostgreSQL CPU利用率监控配置" }
步骤2:在监控消息中引入自定义内容
修改datadog_monitor资源的message部分,把自定义消息插入到合适的位置(比如在系统默认说明之后、通知字符串之前),用Terraform的条件判断处理空值情况,避免空内容占用换行:
resource "datadog_monitor" "aurora_postgres_cpu_utilization_monitor_tf" { count = var.aurora_postgres_cpu_utilization.deploy ? 1 : 0 name = "${var.unique_prefix} - Aurora PostgreSQL RDS CPU Utilization" type = "query alert" query = "avg(last_${var.aurora_postgres_cpu_utilization.query_time}):avg:aws.rds.cpuutilization{%{~if local.monitor_query_string == ""}*%{else}${local.monitor_query_string}%{endif~}} by {region,dbinstanceidentifier} >= ${var.aurora_postgres_cpu_utilization.critical_threshold}" message = <<EOF RDS CPU Usage is averaging {{value}}, which breached current thresholds {{#is_alert}}{{threshold}}{{/is_alert}}{{#is_warning}}{{warn_threshold}}{{/is_warning}} Percentage of CPU utilization. Recommended metric for standard monitoring. Available for Aurora DBs. ${var.aurora_postgres_cpu_utilization.custom_message != "" ? "* __自定义消息__: ${var.aurora_postgres_cpu_utilization.custom_message}\n" : ""} * __Severity__: {{#is_alert}}**Alert**{{/is_alert}}{{#is_warning}}**Warning**{{/is_warning}} * __Value__: {{value}} * __Alert threshold__: {{#is_alert}}{{threshold}}{{/is_alert}}{{#is_warning}}{{warn_threshold}}{{/is_warning}} * __Last triggered at__: {{last_triggered_at}} ({{last_triggered_at_epoch}}) ${local.notification_string} EOF tags = local.monitor_tags include_tags = "true" notification_preset_name = "hide_handles" priority = var.aurora_postgres_cpu_utilization.priority_level restricted_roles = var.aurora_postgres_cpu_utilization.restricted_roles monitor_thresholds { critical = var.aurora_postgres_cpu_utilization.critical_threshold warning = var.aurora_postgres_cpu_utilization.warning_threshold } }
步骤3:使用自定义消息
用户可以在配置文件(比如terraform.tfvars)里设置自定义内容:
aurora_postgres_cpu_utilization = { deploy = true query_time = "5m" critical_threshold = 90 warning_threshold = 75 priority_level = 3 restricted_roles = [] custom_message = "请检查数据库连接数,近期有批量任务执行" }
说明
- 这个方案把自定义消息整合到监控的标准字段列表里,格式统一,看起来更整洁
- 用
optional(string, "")设置默认空值,用户不填的话不会影响原有消息结构 - 条件判断
${var.aurora_postgres_cpu_utilization.custom_message != "" ? "...\n" : ""}确保只有当用户传入内容时才显示这一行,避免空行浪费空间
内容的提问来源于stack exchange,提问作者Devon
相关产品推荐
相关产品推荐

