2
votes

I’m having trouble understanding how to create a loop for my resource below. I need to create multiples resources based on the variable "instance" which is nested within the "dimentions" block. From my understanding after reading some documentation, I should use the for_each parameter, however I can't seem to figure it out.

resource "aws_cloudwatch_metric_alarm" "disk_percentage_low" {
  alarm_name                = "disk_percentage_low"
  comparison_operator       = "LessThanOrEqualToThreshold"
  evaluation_periods        = "1"
  metric_name               = "disk_used_percent"
  namespace                 = "AWS/CWAgent"
  period                    = "60"
  statistic                 = "Average"
  threshold                 = "20"
  alarm_description         = "This metric monitors ec2 disk utilization"
  actions_enabled           = "true" 
  alarm_actions             = [aws_sns_topic.disk_alarm.arn]
  insufficient_data_actions = []
 
  dynamic = "dimensions" {
    for_each = var.instance
    content { 
      instanceid   = var.instanceid
      instancetype = var.instancetype
      imageid      = var.imageid
      instance     = var.instance.value 
    }
  }  
 }

variable "instance" {
  type = list
  default = ["E:" , "D:"]
} 

 

I'm pretty sure I'm doing this wrong, but I've been messing around with it for a few days now and have tried a few different things, none of which seem to work. Any help would be much appreciated, thanks.

1

1 Answers

2
votes

You can't use multiple dimensions in a single alarm in aws_cloudwatch_metric_alarm. Your dimension can be only:

  dimensions = 
      instanceid   = var.instanceid
      instancetype = var.instancetype
      imageid      = var.imageid
      instance     = var.instance[0]
    }

or

  dimensions = 
      instanceid   = var.instanceid
      instancetype = var.instancetype
      imageid      = var.imageid
      instance     = var.instance[1]
    }

If you want alarm for the two values in var.instance you have to create *two alarms:

resource "aws_cloudwatch_metric_alarm" "disk_percentage_low" {

  for_each                  = toset(var.instance)

  alarm_name                = "disk_percentage_low"
  comparison_operator       = "LessThanOrEqualToThreshold"
  evaluation_periods        = "1"
  metric_name               = "disk_used_percent"
  namespace                 = "AWS/CWAgent"
  period                    = "60"
  statistic                 = "Average"
  threshold                 = "20"
  alarm_description         = "This metric monitors ec2 disk utilization"
  actions_enabled           = "true" 
  alarm_actions             = [aws_sns_topic.disk_alarm.arn]
  insufficient_data_actions = []
 
  dimensions = {
      instanceid   = var.instanceid
      instancetype = var.instancetype
      imageid      = var.imageid
      instance     = each.value
    } 
 }