服务器列表的 Cloudwatch 警报

use*_*710 1 amazon-web-services terraform cloudwatch-alarms

我试图在服务器列表中设置一些警报,我在本地定义了我的服务器,如下所示:

  locals {
      my_list = [
        "server1",
        "server2"
      ]
    }
Run Code Online (Sandbox Code Playgroud)

然后我将我的 cloudwatch 警报定义如下:(这是一个这样的警报)

resource "aws_cloudwatch_metric_alarm" "ec2-high-cpu-warning" {
  for_each            = toset(local.my_list)
  alarm_name          = "ec2-high-cpu-warning-for-${each.key}"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = "1"
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  dimensions = {
    instanceid   = values(data.aws_instances.my_instances)[*].ids
    instancename = local.my_list
  }

  period                    = "60"
  statistic                 = "Average"
  threshold                 = "11"
  alarm_description         = "This warning is for high cpu utilization for ${each.key}"
  actions_enabled           = true
  alarm_actions             = [data.aws_sns_topic.my_sns.arn]
  insufficient_data_actions = []
  treat_missing_data        = "notBreaching"
}
Run Code Online (Sandbox Code Playgroud)

我还将数据源定义如下:

data "aws_instances" "my_instances" {

  for_each = toset(local.my_list)

  instance_tags = {
    Name = each.key
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我运行 terraform plan 时,出现错误:

| data.aws_instances.my_instances is object with 2 attributes
Run Code Online (Sandbox Code Playgroud)

属性“dimensions”的值不合适:元素“instanceid”:需要字符串。

Mar*_*cin 5

在你的for_each你应该使用data.aws_instance.my_instances

resource "aws_cloudwatch_metric_alarm" "ec2-high-cpu-warning" {

  for_each            = data.aws_instance.my_instances
  
  alarm_name          = "ec2-high-cpu-warning-for-${each.key}"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = "1"
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  
  dimensions = {
    instanceid   = each.value.id
    instancename = each.key
  }

  period                    = "60"
  statistic                 = "Average"
  threshold                 = "11"
  alarm_description         = "This warning is for high cpu utilization for ${each.key}"
  actions_enabled           = true
  alarm_actions             = [data.aws_sns_topic.my_sns.arn]
  insufficient_data_actions = []
  treat_missing_data        = "notBreaching"
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将为您的两个实例创建两个警报(每个实例一个警报),其中instancename将是server1“server2”。