How can I attach SNS notification to aws_appautoscaling_policy for ECS target tracking in terraform?

778 Views Asked by At

If I have the following terraform, and an SNS topic ARN available, is there a way to attach a cloudwatch notification event to the alarms that AWS creates under the covers?

resource "aws_ecs_service" "service_definition" {
  name                               = "${var.servicename}"
  cluster                            = "${var.name}"
  task_definition                    = "${var.task_definition_arn}"
  desired_count                      = "${var.desired_count}"
  deployment_minimum_healthy_percent = "${var.deployment_minimum_healthy_percent}"

  ordered_placement_strategy {
    field = "attribute:ecs.availability-zone"
    type  = "spread"
  }
}

resource "aws_appautoscaling_target" "ecs_target" {
  max_capacity       = "${var.container_max_count}"
  min_capacity       = "${var.desired_count}"
  resource_id        = "service/${var.clustername}/${var.servicename}"
  role_arn           = "${var.ecs_iam_role}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"

  depends_on = ["aws_ecs_service.service_definition"]
}

resource "aws_appautoscaling_policy" "ecs_scale-memory" {
  name               = "${var.servicename}_scale-memory"
  policy_type        = "TargetTrackingScaling"
  resource_id        = "service/${var.clustername}/${var.servicename}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"

  target_tracking_scaling_policy_configuration {
    target_value       = "${var.target_container_memory_percent}"
    scale_in_cooldown  = "${var.target_scalein_cooldown_seconds}"
    scale_out_cooldown = "${var.target_scaleout_cooldown_seconds}"

    predefined_metric_specification {
      predefined_metric_type = "ECSServiceAverageMemoryUtilization"
    }
  }

  depends_on = ["aws_appautoscaling_target.ecs_target"]
}

AWS creates two alarms for the tracking event:

  • TargetTracking-service/clustername/servicename-AlarmHigh-GUID value
  • TargetTracking-service/clustername/servicename-AlarmLow-GUID value

These have actions to scale up to the desired count via the attached ecs_target. I simply want to attach (via Terraform) a SNS notification for these as well (like one could do for a EC2 scaling event).

1

There are 1 best solutions below

0
On

Since actions are defined as part of the aws_cloudwatch_metric_alarm resource they don't have the ability to be managed independently. Even the aws cli equivalent requires the actions as part of setting up the alarm. Since this portion is abstracted in your case you can't add the SNS topic alert. Your best option is likely creating an additional alarm for each that notifies the SNS topic. You can use describe-alarms to get an idea of how the built in alarms are configured then replicate them in Terraform.