Terraform - Automation of S3 event notification to SNS
This is an automation of https://rsinfomindss.blogspot.com/2023/04/aws-s3-bucket-event-notification.html via terraform.
We will start below modules:
1) Creating an S3 bucket.
2) Creating SNS topics.
3) Creating an SNS topic subscription.
4) Creating S3 bucket notification - Event notification for all S3 events.
While applying you may get 400 errors and it means IAM policy issue with SNS Publish on the S3 service.
We will start with provider configuration.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
#version = "~> 3.21" # Optional but recommended in production
}
}
}
provider "aws" {
region = "us-east-1"
}
# Creating a S3 bucket
module "s3_bucket"{
source = "terraform-aws-modules/s3-bucket/aws"
bucket = "rsinfominds"
versioning = {
enabled = true
}
tags = {
Environment = "Test"
}
}
# Creating SNS topic
module "sns" {
source = "terraform-aws-modules/sns/aws"
name = "rsinfominds-sns"
tags = {
Environment = "Test"
}
}
# Creating subscription using aws sns topic subscription
resource "aws_sns_topic_subscription" "topic-subscription" {
topic_arn = module.sns.topic_arn
protocol = "email"
endpoint = "rsinfominds@gmail.com"
}
# Configuring s3 bucket notification to SNS topic
resource "aws_s3_bucket_notification" "s3-notification" {
bucket = module.s3_bucket.s3_bucket_id
topic {
topic_arn = module.sns.topic_arn
events = ["s3:ObjectCreated:*"]
}
}
data "aws_iam_policy_document" "iam_policy" {
statement {
effect = "Allow"
actions = ["SNS: Publish"]
resources = [module.sns.topic_arn]
principals {
type = "Service"
identifiers = ["s3.amazonaws.com"]
}
}
}
resource "aws_sns_topic_policy" "topic_policy" {
arn = module.sns.topic_arn
policy = data.aws_iam_policy_document.iam_policy.json
}
I tested by uploading an object to the bucket and I got the mail.
Comments
Post a Comment