resource "aws_cloudwatch_metric_alarm" "billing_alarm" {

  alarm_name          = "billing_alarm"
  comparison_operator = "GreaterThanThreshold"
  metric_name         = "EstimatedCharges"
  namespace           = "AWS/Billing"
  evaluation_periods  = "1"
  period              = "21600"
  statistic           = "Maximum"
  threshold           = local.billing_alarm_limit
  alarm_description   = "Billing alarm"

  alarm_actions = [aws_sns_topic.billing_alarm_topic.arn]

  tags = {
    Name        = "billing_alarm_topic_cf"
    CreatedBy   = "terraform"
    Environment = "aws-alarms"
  }
}

# The SNS topic with email subscriptions
# https://medium.com/@raghuram.arumalla153/aws-sns-topic-subscription-with-email-protocol-using-terraform-ed05f4f19b73
resource "aws_sns_topic" "billing_alarm_topic" {
  name = "billing_alarm_topic"
  provisioner "local-exec" {
    command = "sh ${path.module}/scripts/sns_subscription.sh"
    environment = {
      AWS_DEFAULT_REGION = var.region
      sns_arn            = self.arn
      sns_emails         = local.billing_alarm_emails
    }
  }
}
