Skip to content

Instantly share code, notes, and snippets.

@chrisj-au
Last active November 27, 2020 00:19
Show Gist options
  • Save chrisj-au/a57afbef3783d208e123782163eb173b to your computer and use it in GitHub Desktop.
Save chrisj-au/a57afbef3783d208e123782163eb173b to your computer and use it in GitHub Desktop.
Terraform event rule notification ec2 spot
# Useful if EC2 is using spot pricing, receive a 2 minute warning notification. Also tracks state changes but notification will be incomplete (you should create a 2nd event target)
resource "aws_cloudwatch_event_rule" "ec2spotnotification" {
name = "ec2spotnotification"
description = "2 min warning for when a spot instance is going to be reclaimed"
role_arn = ""
event_pattern = <<EOF
{
"source" : [ "aws.ec2" ],
"detail-type": [
"EC2 Spot Interruption Warning",
"EC2 Instance State-change Notification"
]
}
EOF
}
resource "aws_sns_topic" "ec2spotnotificationtopic" {
name = "ec2spotnotification"
}
resource "aws_cloudwatch_event_target" "sns" {
rule = aws_cloudwatch_event_rule.ec2spotnotification.name
target_id = "CWSendToSNS"
arn = aws_sns_topic.ec2spotnotificationtopic.arn
input_transformer {
input_paths = {
account_id = "$.account",
time = "$.time",
region = "$.region",
title = "$.detail-type",
instance-id = "$.detail.instance-id",
action = "$.detail.instance-action"
}
input_template = "\" <title>: <time> - EC2 Instance (<instance-id>) will <action> on account <account_id> in the AWS Region <region>.\""
}
}
resource "aws_sns_topic_policy" "default" {
arn = aws_sns_topic.ec2spotnotificationtopic.arn
policy = data.aws_iam_policy_document.sns_topic_policy.json
}
data "aws_iam_policy_document" "sns_topic_policy" {
statement {
effect = "Allow"
actions = ["SNS:Publish"]
principals {
type = "Service"
identifiers = ["events.amazonaws.com"]
}
resources = [aws_sns_topic.ec2spotnotificationtopic.arn]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment