Example main.tf

provider "aws" {
  # These details are provided for illustration but you should replace them depending on your AWS authentication choices.
  # Similarly, the terraform configuration (for the state storage) has been omitted for brevity.
  region = "<your region>"
  profile = "<your profile>"
}

variable "source_bucket_name" {
  description = "The name of the source S3 bucket"
  type = string
}

variable "sqs_queue_name" {
  description = "The name of the SQS Queue to which created events should be sent"
  type = string
}

resource "aws_s3_bucket" "source_bucket" {
  bucket = var.source_bucket_name

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_sqs_queue" "s3_created_events_sqs_queue" {
  count = var.sqs_queue_name != "" ? 1 : 0
  name = var.sqs_queue_name
}

resource "aws_sqs_queue_policy" "s3_created_events_sqs_queue_policy" {
  count = var.sqs_queue_name != "" ? 1 : 0
  queue_url = aws_sqs_queue.s3_created_events_sqs_queue[0].id
  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Id": "S3SQSPolicy",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "sqs:SendMessage",
      "Resource": "${aws_sqs_queue.s3_created_events_sqs_queue[0].arn}",
      "Condition": {
        "ArnEquals": {
          "aws:SourceArn": "${aws_s3_bucket.source_bucket.arn}"
        }
      }
    }
  ]
}
POLICY
}

resource "aws_s3_bucket_notification" "source_bucket_queue_notification" {
  count = var.sqs_queue_name != "" ? 1 : 0
  bucket = aws_s3_bucket.source_bucket.id

  queue {
    queue_arn = aws_sqs_queue.s3_created_events_sqs_queue[0].arn
    events = ["s3:ObjectCreated:*"]
  }
}

output "s3_created_events_sqs_queue_arn" {
  value = var.sqs_queue_name != "" ? aws_sqs_queue.s3_created_events_sqs_queue[0].arn : null
}

Last updated

Was this helpful?