Search code examples
amazon-web-servicesterraformamazon-cloudwatchcloudwatch-alarms

Iterate through list of servers and create alerts for each server?


I have a list of servers as below for which I need to create cloudwatch alerts. I can't seem to find many examples of this.

variable "vms" {

type = list

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

}

I want to use for_each for my cloudwatch alarms:

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"

}

Edit: I believe i need to do something like this

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"
  }

Solution

  • You can use your var.vms if you want. There is no need for locals. However, in your first attempt you can't use count and for_each at the same time. In your second attempt, you are missing some arguments (statistic and period) and using incorrectly string interpolation.

    Thus, the following should be tried:

    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"
      }
    }
    

    The alarms will not work if your custom metrics don't exist, but I assume that the metrics are working and set correctly.