使用 Terraform 配置 Grafana 告警资源

使用 Terraform 的 Grafana Provider 管理告警资源并部署到 Grafana。Provider 对 Grafana Alerting 的支持,可以让整个告警体系以代码形式创建、管理和维护。

本指南列出部署所需步骤与参考资料。实践演示可克隆并试用Grafana OSS 与 Docker Compose 示例。

用 Terraform 创建和管理告警资源,需要:

  1. 创建 API 认证令牌,配置 Terraform provider。
  2. 通过导出已有告警资源,或编写Terraform 告警资源定义,生成 Terraform 配置。默认不能在界面编辑配置出来的资源;若要允许 Grafana UI 修改,可启用资源的 disable_provenance。
  3. 运行 terraform apply 部署资源。

开始之前,准备 Grafana 实例,并在机器上安装 Terraform。

创建认证令牌并配置 provider

可以创建服务账号令牌,供 Terraform 向 Grafana 认证。用于配置告警资源的步骤:

  1. 新建服务账号。
  2. 赋予访问告警配置 API的角色或权限。
  3. 创建服务账号令牌。
  4. 为令牌命名并保存,以供 Terraform 使用。

进入 Terraform 配置工作目录,创建 main.tf:

terraform {
    required_providers {
        grafana = {
            source = "grafana/grafana"
            version = ">= 2.9.0"
        }
    }
}

provider "grafana" {
    url = <grafana-url>
    auth = <api-key>
}

把 <grafana-url> 替换为 Grafana 实例 URL,<api-key> 替换为刚创建的 API 令牌。

该配置安装 Grafana Terraform provider,并通过令牌认证。其他认证方式(包括基本认证)见 auth 文档。

Grafana Cloud 用户可参阅用 Terraform 管理 Cloud stack。RBAC 参见Terraform 配置 RBAC和告警配置角色 fixed:alerting.provisioning.*。

为告警资源创建 Terraform 配置

Provider 支持以下资源。本节逐项创建配置,并演示如何关联:

告警资源 Terraform 资源
告警规则 grafana_rule_group
联系点 grafana_contact_point
通知模板 grafana_message_template
通知策略树 grafana_notification_policy
静默时段 grafana_mute_timing

添加告警规则

告警规则查询任意后端 Grafana 数据源,并据此发出告警。

  1. 先创建要查询的数据源以及存放规则的文件夹。本例使用 TestData 数据源。
resource "grafana_data_source" "<terraform_data_source_name>" {
    name = "TestData"
    type = "testdata"
}

resource "grafana_folder" "<terraform_folder_name>" {
    title = "My Rule Folder"
}

<terraform_data_source_name> 替换为数据源的 Terraform 名称,<terraform_folder_name> 替换为文件夹的 Terraform 名称。

  1. 在 Grafana 中创建或找到要导入的告警规则。
  2. 以 Terraform 格式导出规则组,得到 grafana_rule_group。可编辑导出配置,也可从零编写:
resource "grafana_rule_group" "<terraform_rule_group_name>" {
    name = "My Alert Rules"
    folder_uid = grafana_folder.<terraform_folder_name>.uid
    interval_seconds = 60
    org_id = 1

    rule {
        name = "My Random Walk Alert"
        condition = "C"
        for = "0s"

        // Query the datasource.
        data {
            ref_id = "A"
            relative_time_range {
                from = 600
                to = 0
            }
            datasource_uid = grafana_data_source.<terraform_data_source_name>.uid
            // `model` is a JSON blob that sends datasource-specific data.
            // It's different for every datasource. The alert's query is defined here.
            model = jsonencode({
                intervalMs = 1000
                maxDataPoints = 43200
                refId = "A"
            })
        }

        // The query was configured to obtain data from the last 60 seconds. Let's alert on the average value of that series using a Reduce stage.
        data {
            datasource_uid = "__expr__"
            // You can also create a rule in the UI, then GET that rule to obtain the JSON.
            // This can be helpful when using more complex reduce expressions.
            model = <<EOT
{"conditions":[{"evaluator":{"params":[0,0],"type":"gt"},"operator":{"type":"and"},"query":{"params":["A"]},"reducer":{"params":[],"type":"last"},"type":"avg"}],"datasource":{"name":"Expression","type":"__expr__","uid":"__expr__"},"expression":"A","hide":false,"intervalMs":1000,"maxDataPoints":43200,"reducer":"last","refId":"B","type":"reduce"}
EOT
            ref_id = "B"
            relative_time_range {
                from = 0
                to = 0
            }
        }

        // Now, let's use a math expression as our threshold.
        // We want to alert when the value of stage "B" above exceeds 70.
        data {
            datasource_uid = "__expr__"
            ref_id = "C"
            relative_time_range {
                from = 0
                to = 0
            }
            model = jsonencode({
                expression = "$B > 70"
                type = "math"
                refId = "C"
            })
        }
    }
}

将 <terraform_rule_group_name> 替换为规则组名称。不同 Grafana 资源通过 Terraform 配置中的 uid 关联;部署时会随机生成该值。为关联规则组与对应数据源、文件夹,把 <terraform_data_source_name> 与 <terraform_folder_name> 替换为此前定义的 Terraform 名称。

接着添加其他资源,或直接进入后文的 Terraform CLI 部署步骤。

添加联系点

联系点是告警通知的接收方。先在 Grafana 创建或找到联系点,也可以按示例编写。以 Terraform 格式导出联系点,得到 grafana_contact_point,必要时编辑。本示例将在周末静默通知:

 resource "grafana_contact_point" "<terraform_contact_point_name>" {
     name = "My contact point email"

     email {
         addresses               = ["<email_address>"]
     }
 }

<terraform_contact_point_name> 替换为联系点的 Terraform 名称,供其他资源引用;<email_address> 替换为接收通知的邮箱。继续添加资源,或用 Terraform CLI 部署。

添加并启用通知模板

通知模板可以在多个联系点之间复用自定义通知。创建或找到要导入的模板组,也可直接写配置;以 Terraform 格式导出模板组,得到 grafana_message_template。

本例创建名为 custom_emails 的组,定义 custom_email.message 模板:

 resource "grafana_message_template" "<terraform_message_template_name>" {
     name = "custom_emails"

     template = <<EOT
 {{ define "custom_email.message" }}
 Lorem ipsum - Custom alert!
 {{ end }}
 EOT
 }

联系点由此可以使用组内通过 {{ define "<NAME>"}} 定义的模板。修改前面的联系点,将 email.message 设为:

 resource "grafana_contact_point" "<terraform_contact_point_name>" {
     name = "My contact point email"

     email {
         addresses               = ["<email_address>"]
         message                 = "{{ template \"custom_email.message\" .}}"
     }
 }

继续添加资源,或使用 Terraform CLI 部署。

添加静默时段

静默时段会在预定区间暂停告警通知。创建或找到要导入的静默时段,也可直接编写;以 Terraform 格式导出,得到 grafana_mute_timing,必要时编辑。

以下示例在周末关闭通知:

 resource "grafana_mute_timing" "<terraform_mute_timing_name>" {
     name = "No weekends"

     intervals {
         weekdays = ["saturday", "sunday"]
     }
 }

把 <terraform_mute_timing_name> 替换为资源的 Terraform 名称,供通知策略树引用。继续添加资源,或使用 Terraform CLI 部署。

添加通知策略树

通知策略定义告警实例如何路由至联系点。

找到默认通知策略树,也可以直接按示例编写。以 Terraform 格式导出策略树,得到 grafana_notification_policy:

resource "grafana_notification_policy" "my_policy_tree" {
contact_point = grafana_contact_point.<terraform_contact_point_name>.name
...

policy {
    contact_point = grafana_contact_point.<terraform_contact_point_name>.name

    matcher {...}

    mute_timings = [grafana_mute_timing.<terraform_mute_timing_name>.name]
}
}

为了把此前的静默时段与联系点关联到策略树,将联系点和静默时段引用分别替换为已定义资源的 Terraform 名称。继续添加资源,或使用 Terraform CLI 部署。

启用多棵通知策略树

默认情况下,Grafana 使用上述 grafana_notification_policy,把所有告警路由至默认策略树。多棵通知策略树允许拆开路由逻辑,例如每个团队一棵树。每棵树通过独立的 grafana_apps_notifications_routingtree_v1beta1 配置。

先为每个作用范围创建路由树:

resource "grafana_apps_notifications_routingtree_v1beta1" "team_platform" {
    metadata {
        uid = "platform-routing-tree"
    }
    spec {
         # ...
    }
}

metadata.uid 设置唯一标识。告警规则引用它,把通知路由至该树而非默认树;具体配置见资源文档。

要让规则路由至指定树,用 grafana_apps_rules_alertrule_v0alpha1 定义规则,把 notification_settings.named_routing_tree.routing_tree 设置为树的 metadata.uid:

resource "grafana_apps_rules_alertrule_v0alpha1" "platform_rule_test" {
    metadata {
        uid        = "platform_rule_test"
        folder_uid = grafana_folder.platform_alert_folder.uid
    }
    spec {
        title = "rule_test"
        # ...
        notification_settings {
            named_routing_tree {
                routing_tree = "platform-routing-tree"
            }
        }
    }
}

不设置 notification_settings.named_routing_tree 的规则仍使用默认策略树。继续添加资源,或使用 Terraform CLI 部署。

允许在 Grafana UI 编辑资源

默认不能在 Grafana 编辑 Terraform 配置的资源,这使告警体系始终与 Terraform 代码同步。若要允许 UI 编辑,在告警资源上启用 disable_provenance:

resource "grafana_contact_point" "my_contact_point" {
  name = "My Contact Point"

  disable_provenance = true
}

resource "grafana_message_template" "custom_notification_template_group" {
  name     = "custom_notification_template_group"
  template = "{{define \"template1\" }}Say{{ end }}{{define \"template2\" }}Hi!{{ end }}"

  disable_provenance = true
}
...

使用 Terraform 部署 Grafana 资源

用 Terraform CLI 创建前述资源:

  1. 初始化包含配置文件的工作目录:
terraform init

该命令初始化目录,安装 main.tf 配置的 Grafana provider。

  1. 应用配置文件以部署资源:
terraform apply

更改 Grafana 之前,Terraform 会展示执行计划并请求确认:

 Plan: 4 to add, 0 to change, 0 to destroy.

 Do you want to perform these actions?
 Terraform will perform the actions described above.
 Only 'yes' will be accepted to approve.

 Enter a value:

确认继续后,Terraform 将创建资源:

Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

现在可以打开 Grafana,验证各项资源是否已创建。

更多示例

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容