skip to Main Content

i want that in my email send notification, when for example in dev created spot instance or created spot instance request, but email not send. what is wrong in this code?

resource "aws_sns_topic" "spot_instance_notification" {
  name = "SpotInstanceNotificationTopic"
}

resource "aws_cloudwatch_event_rule" "spot_instance_creation_rule" {
  name = "SpotInstanceCreationRule"

  event_pattern = <<EOF
  {
    "source": ["aws.ec2"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail": {
      "eventSource": [
      "ec2.amazonaws.com",
      "rds.amazonaws.com",
      "s3.amazonaws.com"
    ],
      "eventName": ["RequestSpotInstances"]
    }
  }
  EOF
}

resource "aws_cloudwatch_event_target" "sns_target" {
  rule        = aws_cloudwatch_event_rule.spot_instance_creation_rule.name
  target_id   = "spot-instance-sns-target"
  arn         = aws_sns_topic.spot_instance_notification.arn
}

resource "aws_sns_topic_subscription" "email_subscription" {
  topic_arn = aws_sns_topic.spot_instance_notification.arn
  protocol  = "email"
  endpoint  = "[email protected]" 
}

2

Answers


  1. Chosen as BEST ANSWER

    Thank you. i use this code

    but notification has a very bad form, how i can correct it?

        resource "aws_sns_topic_policy" "topic_policy" {
      arn = aws_sns_topic.spot_instance_notification.arn
    
      policy = jsonencode({
        Version = "2012-10-17",
        Statement = [
          {
            Sid = "AllowEventBridgeToPublish",
            Effect = "Allow",
            Principal = {
              Service = "events.amazonaws.com"
            },
            Action = "SNS:Publish",
            Resource = aws_sns_topic.spot_instance_notification.arn,
          }
        ]
      })
    }
    

  2. In the resource documentation, there is a note:

    In order to be able to have your AWS Lambda function or SNS topic invoked by an EventBridge rule, you must set up the right permissions using aws_lambda_permission or aws_sns_topic_policy.

    So that means you need to add the SNS topic policy, which would allow the EventBridge rule to invoke the SNS topic. The documentation for the topic policy is here. You can take a look in the AWS documentation for the SNS topic policy example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search