Reputation: 163
Here is an example of a cloudwatch_metric_alarm resource
:
resource "aws_cloudwatch_metric_alarm" "nlb_healthyhosts" {
alarm_name = "alarmname"
comparison_operator = "LessThanThreshold"
evaluation_periods = "1"
metric_name = "HealthyHostCount"
namespace = "AWS/NetworkELB"
period = "60"
statistic = "Average"
threshold = var.logstash_servers_count
alarm_description = "Number of healthy nodes in Target Group"
actions_enabled = "true"
alarm_actions = [aws_sns_topic.sns.arn]
ok_actions = [aws_sns_topic.sns.arn]
dimensions = {
TargetGroup = aws_lb_target_group.lb-tg.arn_suffix
LoadBalancer = aws_lb.lb.arn_suffix
}
}
I still don't understand the Alarm Actions Argument. In the terraform documentation, we have:
alarm_actions - (Optional) The list of actions to execute when this alarm transitions into an ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN).
Could someone give me a concrete example for that, for example sending an Email / and / Creating an SNS Topic ( without an exiting topic ARN ).
I thank you so much in advance for your help.
Upvotes: 6
Views: 9681
Reputation: 1698
If you are looking for an example, it would looks like as follow.
First you need to create your alarm and in the in the alarm actions field reference to your sns topic arn:
resource "aws_cloudwatch_metric_alarm" "nlb_healthyhosts" {
alarm_name = "alarmname"
comparison_operator = "LessThanThreshold"
evaluation_periods = "1"
metric_name = "HealthyHostCount"
namespace = "AWS/NetworkELB"
period = "60"
statistic = "Average"
threshold = var.logstash_servers_count
alarm_description = "Number of healthy nodes in Target Group"
actions_enabled = "true"
alarm_actions = [aws_sns_topic.alarm.arn]
dimensions = {
TargetGroup = aws_lb_target_group.lb-tg.arn_suffix
LoadBalancer = aws_lb.lb.arn_suffix
}
}
Then create the SNS topic and subscribe your email to that topic:
# SNS topic to send emails with the Alerts
resource "aws_sns_topic" "alarm" {
name = "my-alarm-topic"
kms_master_key_id = aws_kms_key.sns_encryption_key.id
delivery_policy = <<EOF
{
"http": {
"defaultHealthyRetryPolicy": {
"minDelayTarget": 20,
"maxDelayTarget": 20,
"numRetries": 3,
"numMaxDelayRetries": 0,
"numNoDelayRetries": 0,
"numMinDelayRetries": 0,
"backoffFunction": "linear"
},
"disableSubscriptionOverrides": false,
"defaultThrottlePolicy": {
"maxReceivesPerSecond": 1
}
}
}
EOF
## This local exec, suscribes your email to the topic
provisioner "local-exec" {
command = "aws sns subscribe --topic-arn ${self.arn} --protocol email --notification-endpoint ${var.your_email} --region ${var.main_region}"
}
}
## KMS Key to encrypt the SNS topic (security best practises)
resource "aws_kms_key" "sns_encryption_key" {
description = "alarms sns topic encryption key"
deletion_window_in_days = 30
enable_key_rotation = true
}
Upvotes: 7