'Is there a better way to create multiple cloudwatch alarms?

I'm trying to create cloudwatch alarms for some specific load balancers.

What if I have to create 100 cloudwatch alarms, do I need to populate the tfvars the way, I'm updating it currently, or is there any other way which is more optimized.

Following is my code.

main.tf

resource "aws_cloudwatch_metric_alarm" "UnHealthyHosts" {
  for_each = var.cloudwatch_alarms_map

  alarm_name          = each.key                                
  comparison_operator = var.cloudwatch_alarm_operator           
  evaluation_periods  = var.cloudwatch_alarm_evaluation_periods 
  metric_name         = var.cloudwatch_alarm_metric             
  namespace           = each.value["alarm_namespace"]           
  period              = var.cloudwatch_alarm_period             
  statistic           = var.cloudwatch_alarm_statistic          
  threshold           = var.cloudwatch_alarm_threshold          
  alarm_description   = var.cloudwatch_alarm_description        
  actions_enabled     = var.cloudwatch_alarm_actions_enabled    
  alarm_actions       = [aws_sns_topic.sns.arn]                 

  dimensions = {
    TargetGroup  = each.value["target_group_arn"]
    LoadBalancer = each.value["load_balancer_arn"]
  }
}

variables.tf

variable "cloudwatch_alarms_map" {
  type = map(object({
    alarm_namespace          = string # eg: AWS/ApplicationELB
    target_group_arn  = string
    load_balancer_arn = string
  }))
  default     = {}
}

terraform.tfvars

cloudwatch_alarms_map = {
    app1-unhealthy-alarm = {
      target_group_arn_suffix  = "targetgroup/sample-app1-tg/12de123e123123aa"
      load_balancer_arn_suffix = "app/sample-alb-app1-lb/12c5732bd012e47a"
      alarm_namespace          = "AWS/ApplicationELB"
    }
    app2-unhealthy-alarm = {
      target_group_arn_suffix  = "targetgroup/sample-app2-tg/313e7f1ad4a2e373"
      load_balancer_arn_suffix = "app/sample-alb-app2-lb/f2c5132bd012e47a"
      alarm_namespace          = "AWS/ApplicationELB"
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source