1

我有一个服务器列表,如下所示,我需要为其创建 cloudwatch 警报。我似乎找不到很多这样的例子。

variable "vms" {

type = list

default = ["server1","server2","server3"]

}

我想将 for_each 用于我的 cloudwatch 警报:

resource "aws_cloudwatch_metric_alarm" "ec2-warning" {

count = length(var.vms)

for_each = {for vms in var.vms: vm.host => vms}

alarm_name = 

comparison_operator = "GreaterThanThreshold"

evaluation_periods = "1"

metric_name = "disk_used_percent"

namespace = "CWAgent"

dimensions = {

path = "/"

fstype = "xfs"

host = data.aws_instance.myec2.private_

dnsdevice = "xvda1"

}

编辑:我相信我需要做这样的事情

locals {
  my_list = [
    "server1",
    "server2",
    "server3",
    "server4"
  ]
}

resource "aws_cloudwatch_metric_alarm" "ec2-disk-space-warning-for" {
  for_each = toset(local.my_list)
  alarm_name          = {each.key}-"ec2-disk-space-warning"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = "1"
  metric_name         = "disk_used_percent"
  namespace           = "CWAgent"
  dimensions = {
    path   = "/"
    fstype = "xfs"
    host   = {each.key}
    device = "xvda1"
  }
4

2 回答 2

1

如果你愿意,你可以使用你的var.vms。没有必要locals。但是,在您的第一次尝试中,您不能同时使用countand for_each。在您的第二次尝试中,您缺少一些参数(statisticperiod) 并错误地使用了 字符串插值

因此,应尝试以下方法:

variable "vms" {
   type = list
   default = ["server1","server2","server3"]
}


resource "aws_cloudwatch_metric_alarm" "ec2-disk-space-warning-for" {
  for_each            = toset(var.vms)
  alarm_name          = "${each.key}-ec2-disk-space-warning"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = "1"
  metric_name         = "disk_used_percent"
  namespace           = "CWAgent"
  statistic           = "Average"
  period              = 60
  dimensions = {
    path   = "/"
    fstype = "xfs"
    host   = each.key
    device = "xvda1"
  }
}

如果您的自定义指标不存在,警报将不起作用,但我假设指标正常工作并且设置正确。

于 2021-01-01T12:35:32.217 回答
0

这终于对我有用

locals {
  my_list = [
    "server1",
    "server2",
    "server3",
    "server4"
  ]
}

resource "aws_cloudwatch_metric_alarm" "ec2-disk-space-warning" {
  for_each            = toset(local.my_list)
  alarm_name          = "ec2-disk-space-warning-for-${each.key}"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = "1"
  metric_name         = "disk_used_percent"
  namespace           = "CWAgent"
  dimensions = {
    path   = "/"
    fstype = "xfs"
    host   = each.key
    device = "xvda1"
  }
于 2021-01-01T12:38:38.467 回答