retrieve instance id to create cloudwatch alarm

Viewed 23

I'm trying to create a Cloudwatch alarm using Terraform, to alert when the EC2 disk space exceeds a certain threshold such as 75%. The below module works fine if I hard-code the instance id. However I would like the alarm to automatically pick up the new instance id, if the instance terminates & launches a new instance via auto-scaling. Any suggestions much appreciated, thanks.

resource "aws_cloudwatch_metric_alarm" "disk_space_alarm" {
  alarm_name          = var.disk_space_alarm_name
  comparison_operator = var.comparison_operator
  evaluation_periods  = var.disk_space_alarm_evaluation_periods
  metric_name         = "disk_used_percent"
  namespace           = "CWAgent"
  period              = var.disk_space_alarm_period
  statistic           = "Average"
  threshold           = var.disk_space_alarm_threshold
  alarm_description   = var.disk_space_alarm_description
  alarm_actions       = [var.notify_alert_arn]
  treat_missing_data  = var.disk_space_alarm_missing_data

  dimensions = {
    "path"                  = "/"
    "InstanceId"            = "i-01234567890"
    "AutoScalingGroupName"  = var.autoscaling_group_name
    "ImageId"               = "var.ami_id"
    "InstanceType"          = "var.instance_type"
    "device"                = "nvme0n1p1"
    "fstype"                = "xfs"
  }
}
1 Answers

Maybe you can reference the id with something like:

instanceid = aws_instance.your_instance.id

Another way I can think of is using outputs and reference the output of the id.

resource "aws_instance" "app_server" {
  ami           = "ami-08d70e59c07c61a3a"
  instance_type = "t2.micro"

  tags = {
    Name = var.instance_name
  }
}

output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.app_server.id
}

instanceid = output.instance_id

https://learn.hashicorp.com/tutorials/terraform/aws-outputs?in=terraform/aws-get-started

Related