1. Answers
  2. Publishing S3 Bucket Events to SNS Topics

How do I publish S3 bucket events to SNS topics?

In this guide, we will demonstrate how to publish events from an S3 bucket to an SNS topic using Pulumi in TypeScript. This setup is useful for building event-driven architectures where actions are triggered by changes in an S3 bucket.

We will create:

  1. An S3 bucket to store objects.
  2. An SNS topic to publish notifications.
  3. An S3 bucket notification configuration to send events to the SNS topic.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Create an SNS topic
const topic = new aws.sns.Topic("myTopic", {
    displayName: "My S3 Events Topic",
});

// Create an S3 bucket
const bucket = new aws.s3.Bucket("myBucket", {
    bucket: "my-bucket-for-events",
});

// Create an SNS topic policy to allow S3 to publish to it
const topicPolicy = new aws.sns.TopicPolicy("myTopicPolicy", {
    arn: topic.arn,
    policy: pulumi.interpolate`{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "Service": "s3.amazonaws.com"
                },
                "Action": "sns:Publish",
                "Resource": "${topic.arn}",
                "Condition": {
                    "ArnLike": {
                        "aws:SourceArn": "${bucket.arn}"
                    }
                }
            }
        ]
    }`,
});

// Create an S3 bucket notification to send events to the SNS topic
const bucketNotification = new aws.s3.BucketNotification("myBucketNotification", {
    bucket: bucket.id,
    topics: [{
        topicArn: topic.arn,
        events: ["s3:ObjectCreated:*"],
        filterPrefix: "images/",
        filterSuffix: ".jpg",
    }],
}, { dependsOn: [topicPolicy] });

export const bucketName = bucket.bucket;
export const topicArn = topic.arn;
export const notificationId = bucketNotification.id;

Key Points:

  • SNS Topic: Created to receive notifications.
  • S3 Bucket: Created to store objects and generate events.
  • Topic Policy: Configured to allow the S3 bucket to publish to the SNS topic.
  • Bucket Notification: Configured to send specific events (e.g., object creation) to the SNS topic.

Summary

In this example, we created an S3 bucket and an SNS topic, set up the necessary permissions, and configured the bucket to send notifications to the SNS topic for specific events. This setup enables event-driven workflows where actions can be triggered by changes in the S3 bucket.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up