Created
July 25, 2021 08:34
-
-
Save matgou/a0b90a732eee27d87d8fa2b678f327fd to your computer and use it in GitHub Desktop.
terraform AWS ec2 evnets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################################ | |
# Terraform : install cloudwatch event | |
################################################################################ | |
terraform { | |
required_providers { | |
aws = { | |
source = "hashicorp/aws" | |
version = "~> 3.27" | |
} | |
} | |
required_version = ">= 0.14.9" | |
} | |
provider "aws" { | |
profile = "default" | |
region = "eu-west-2" | |
} | |
################################################################################ | |
# Cloudwatch event | |
################################################################################ | |
resource "aws_cloudwatch_event_rule" "stateupdate" { | |
name = "capture-ec2-instance-state-change" | |
description = "Capture State-change of an ec2 instance" | |
event_pattern = <<EOF | |
{ | |
"source": [ | |
"aws.ec2" | |
], | |
"detail-type": [ | |
"EC2 Instance State-change Notification" | |
] | |
} | |
EOF | |
} | |
################################################################################ | |
# SNS Topic | |
################################################################################ | |
resource "aws_sns_topic" "ec2_instance_state_updates" { | |
name = "ec2-state-updates-topic" | |
} | |
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.ec2_instance_state_updates.arn] | |
} | |
} | |
resource "aws_sns_topic_policy" "default" { | |
arn = aws_sns_topic.ec2_instance_state_updates.arn | |
policy = data.aws_iam_policy_document.sns_topic_policy.json | |
} | |
################################################################################ | |
# Cloudwatch event : SNS Target | |
################################################################################ | |
resource "aws_cloudwatch_event_target" "sns" { | |
rule = aws_cloudwatch_event_rule.stateupdate.name | |
target_id = "SendToSNS" | |
arn = aws_sns_topic.ec2_instance_state_updates.arn | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment