'Terraform to create multiple alarms for Windows logical disk free space on EC2 instances

I'm trying to create a CloudWatch alarms for Windows logical disk Terraform Enterprise Edition ver 0.13.7 Collecting data for metrics CW agent config snippet

"metrics": {
        "namespace": "custom_namespace",
        "append_dimensions": {
            "ImageId": "${aws:ImageId}",
            "InstanceId": "${aws:InstanceId}",
            "InstanceType": "${aws:InstanceType}"
        },
        "metrics_collected": {
            "LogicalDisk": {
                "measurement": [
                    {"name": "% Free Space", "unit": "Percent"}
                ],
                "metrics_collection_interval": 60,
                "resources": [
                    "*"
                ]
            },

Terraform code

data.tf

To get info from the servers

data "aws_instance" "instance_name" {
  for_each      = toset(data.aws_instances.instance_cloudwatch.ids)
  instance_id   = each.value
 }

to iterate through all servers with the specific tag

data "aws_instances" "instance_cloudwatch" {
  instance_tags = {
    Type        = var.type
  }
}

disk.tf

module "cloudwatch-metric-alarm-disk-usage" {
  source = "git::ssh://[email protected]:7999/corecard/modules-cloudwatch.git//cw_metric_alarm?ref=v6.0"
  for_each                  = toset(data.aws_instances.instance_cloudwatch.ids)
  
  alarm_name                = "${var.app_prefix}-${var.type}-disk-utilization-alarm-${var.environment}-${data.aws_instance.instance_name[each.value].tags["Name"]}"

Alarm name includes the instance name Also needs to include the disk for uniqueness

  comparison_operator       = "GreaterThanOrEqualToThreshold"
  evaluation_periods        = "2"
  metric_name               = "LogicalDisk % Free Space"

Custom metrics with that name

namespace                 = var.name_space != "" ?  var.name_space : "CC-${upper(var.type)}"

For non-standard namespace

  statistic                 = "Average"
  threshold                 = "2"
  period                    = "60"
  alarm_description         = "Alarm to trigger PagerDuty when disk utilization is high"
  insufficient_data_actions = []
  alarm_actions             = [aws_sns_topic.sns_general.arn]
  dimensions = {
    InstanceId   = each.value
    ImageId      = data.aws_instance.instance_name[each.value].ami
    InstanceType = data.aws_instance.instance_name[each.value].instance_type
    objectname   = "LogicalDisk"

   instance     = "C:" 

<--- need to iterate through all disks

  }  
}


Sources

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

Source: Stack Overflow

Solution Source