How to create Cloudwatch Alarm of EKS Nodes via Terraform

4/26/2021

I'm trying to create an alarm of a EKS Nodes by terraform but I'm not able to do it, because I don't know how to do a reference of the node instances. I have this code:

resource "aws_cloudwatch_metric_alarm" "cpu_high_nodes" {
  for_each   = local.ob
  
  alarm_name          = "${var.cluster_name}-nodes-cpu-high-${each.value}"
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "2"
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  period              = "300"
  statistic           = "Maximum"
  threshold           = "85"
  alarm_description   = "Scale up if the cpu avg is above 85% for 10 minutes"

dimensions = {
    InstanceId =  "instance-id"
 }

If I put the InstanceId by hand, the alarm works perfectly,but problem is to get an output from the task which create the nodes..

resource "aws_launch_template" "worker-node" {
  for_each               = local.ob

  image_id               = "ami-038341f2c72928ada"
  name                   = "${var.cluster_name}-worker-node-${each.value}"
  instance_type          = "t3.medium"

  block_device_mappings {
    device_name = "/dev/xvda"

    ebs {
      volume_size = 20
      volume_type = "gp2"
    }
  }
  user_data                     = base64encode(data.template_file.user_data.template)
  tag_specifications {
    resource_type = "instance"
    tags = {
      "Instance Name" = "${var.cluster_name}-node-${each.value}"
       Name = "${var.cluster_name}-node-${each.value}"
    }
  }
}

If I get .id of this task I'm getting de launch template ID and actually I need the EC2 instance ID, but I don't know how to get it..

ANy idea?

THx

-- Humberto Lantero
amazon-eks
amazon-web-services
kubernetes
terraform

0 Answers