DEV Community

katryo
katryo

Posted on

AWS CDK sample with Existing S3 bucket and existing SNS topic

You cannot add a new S3 notification to existing S3 buckets by CloudFormation. However, you can add an SQS subscription to existing SNS topics.

S3 => SNS topic => SQS subscription => Lambda

import core = require("@aws-cdk/core");
import lambda = require("@aws-cdk/aws-lambda");
import s3 = require("@aws-cdk/aws-s3");
import sns = require("@aws-cdk/aws-sns");
import sqs = require("@aws-cdk/aws-sqs");
import { SqsEventSource } from "@aws-cdk/aws-lambda-event-sources";
import { SqsSubscription } from "@aws-cdk/aws-sns-subscriptions";

export class ExistingS3BucketAndSNSTopicToLambdaThroughSQS extends core.Construct {
  constructor(scope: core.Construct, id: string) {
    super(scope, id);

    const bucket = s3.Bucket.fromBucketName(
      this,
      "ExistingS3Bucket",
      "bucketName"
    );

    const handler = new lambda.Function(this, "lambda", {
      runtime: lambda.Runtime.NODEJS_10_X,
      code: lambda.Code.asset("lambda/dist"),
      handler: "index.main",
      timeout: core.Duration.seconds(30),
      environment: {
        BUCKET_NAME: bucket.bucketName
      }
    });

    bucket.grantRead(handler);

    const topic = sns.Topic.fromTopicArn(
      this,
      "ExistingSNSTopic",
      `arn:${core.Aws.PARTITION}:sns:${core.Aws.REGION}:${core.Aws.ACCOUNT_ID}:existing-sns-topic`
    );
    const queue = new sqs.Queue(this, "queue");

    topic.addSubscription(new SqsSubscription(queue));

    handler.addEventSource(
      new SqsEventSource(queue, {
        batchSize: 1
      })
    );
  }
}

This example is working well with AWS CDK v1.6.1. In the future it might be broken because AWS CDK is in its public beta.

Gist: https://gist.github.com/katryo/ff3cf8b5e3f12823ad7bc2468db054cd

Top comments (0)