Set the SNS topic ARN as an alarm action on the CloudWatch alarm. CloudWatch publishes directly to SNS on every state transition.resource "aws_cloudwatch_metric_alarm" "example" {
alarm_name = "high-cpu-utilization"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = 2
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = 120
statistic = "Average"
threshold = 80
alarm_description = "CPU utilization exceeded 80% for 4 minutes."
dimensions = {
InstanceId = "i-1234567890abcdef0"
}
alarm_actions = [module.notify_slack.slack_topic_arn]
ok_actions = [module.notify_slack.slack_topic_arn]
insufficient_data_actions = [module.notify_slack.slack_topic_arn]
}
Adding the SNS topic to ok_actions and insufficient_data_actions ensures you receive a Slack notification for every state change, not just when an alarm fires.
Use an EventBridge rule to forward CloudWatch alarm state change events to the SNS topic.resource "aws_cloudwatch_event_rule" "cloudwatch_alarms" {
name = "forward-cloudwatch-alarms"
description = "Forward CloudWatch alarm state changes to Slack"
event_pattern = jsonencode({
source = ["aws.cloudwatch"]
detail-type = ["CloudWatch Alarm State Change"]
})
}
resource "aws_cloudwatch_event_target" "cloudwatch_alarms_sns" {
rule = aws_cloudwatch_event_rule.cloudwatch_alarms.name
target_id = "SendToSNS"
arn = module.notify_slack.slack_topic_arn
}
EventBridge delivers a different event structure than the native CloudWatch alarm action. The native alarm action payload shown in the example above is what the formatter expects, so the alarm action approach is generally simpler.