How to loop within a nested block

Hi,

I’m having trouble understanding how to create a loop for my resource below. I need to create two of these resources and the variable of which the number of resources is dependent on is within the nested block “dimensions”, “instance = var.instance”, (highlighted in bold - which represents the disk partitions on an EC2 instance). From my understanding after reading some documentation, I cannot use the count parameter for this?

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 =

dimensions = {
instanceid = var.instanceid
instance = var.instance
instancetype = var.instancetype
imageid = var.imageid
}
}

My vague understanding is that I need to use the dynamic “tag” and the “for_each” expression?

I would really appreciate any help. Thanks for your time.

Hi,

I’ve now figured out how to do this. Please go ahead and close this, thanks.

The way to do this is the following:

resource “aws_cloudwatch_metric_alarm” “disk_percentage_low” {

for_each = toset(var.instance)

alarm_name = “disk_percentage_low_${each.value}”
comparison_operator = “LessThanOrEqualToThreshold”
evaluation_periods = “1”
metric_name = “LogicalDisk % Free Space”
namespace = “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
objectname = var.objectname
}
}

1 Like