Terraform 自己查找和填充 AWS cloudwatch 警报

Terraform to lookup and fill AWS cloudwatch alarm itself

所以我有一个主要的 RDS 模块,它引用了另一个名为“cloudwatch_alarms”的模块。

我在 4 个不同的环境中使用同一个模块,每个环境中的每个警报都有不同的“阈值”值..所以我不能为它保留一个值。 所以我希望我的代码以变量 - terraform 自动获取每个警报的值(来自 AWS)的方式进行更改。

有办法吗?

我的模块如下:

main.tf 模块 RDS 的一部分:

...
...

module "alarmA" {
  source = "git@github.com:cloudwatch_alarms"

  alarm_description        = "xxx"
  alarm_name               = "${var.name}-alarmA"
  comparison_operator      = "LessThanOrEqualToThreshold"
  evaluation_periods       = 4
  namespace                = "AWS/RDS"
  notification_topic       = [var.notification_topic]
  period                   = 6
  threshold                = 15000
}

module "alarmB" {
  source = "git@github.com:cloudwatch_alarms"

  alarm_description        = "xxxx"
  alarm_name               = "${var.name}-alarmB"
  comparison_operator      = "GreaterThanOrEqualToThreshold"
  evaluation_periods       = 5
  namespace                = "AWS/RDS"
  notification_topic       = [var.notification_topic]
  period                   = 7
  threshold                = 25000
}

模块 cloudwatch_alarms 的 main.tf 部分:

resource "aws_cloudwatch_metric_alarm" "alarm" {
  count = var.alarm_count

  alarm_description   = var.alarm_description
  alarm_name          = var.alarm_count > 1 ? format("%v-%03d", local.alarm_name, count.index + 1) : local.alarm_name
  alarm_actions       = []
  comparison_operator = var.comparison_operator
  datapoints_to_alarm = var.datapoints_to_alarm
  dimensions          = var.dimensions[count.index]
  evaluation_periods  = var.evaluation_periods
  metric_name         = var.metric_name
  namespace           = var.namespace
  period              = var.period
  statistic           = var.statistic
  threshold           = var.threshold
  unit                = var.unit

variable.tf 共 cloudwatch_alwarms:

variable "threshold" {
  description = "The value against which the specified statistic is compared."
  type        = string
}

假设我对您的问题的理解是正确的,您不能在 terraform 中引用现有的 AWS 警报,因为它 不提供 data sources for alarms. The only sources provided by TF are aws_cloudwatch_log_group and aws_cloudwatch_event_source. To overcome that you would have to develop your own External Data Source 使用,例如bash 中的 AWS CLI,如链接的 TF 文档中所示。

但是,如果这些警报是您的 子模块 outputs,您可以在父模块中引用它们。为此,您必须将子模块修改为 output 每个警报的阈值。然后,在父模块中,您可以简单地获取这些输出值并将它们用于其他目的,例如通过将它们传递给其他子模块。