Is it sufficient to define SNS topic as a function event?

Hi,

I’m fairly new to the Serverless framework, and I have a question the answer to which I haven’t been able to find in this forum.

I have a lambda function that will be triggered by SNS:

functions:
  registerHostnames:
    handler: index.handler
    events:
    - sns:
        topicName: register-hostname-topic
        displayName: Register hostnames after a new deployment

Do I need to specifically define/create an SNS Topic as a resource as well, like so:

resources:
  Resources:
    Type: "AWS::SNS::Topic"
    Properties:
      DisplayName: Register hostnames after a new deployment
      TopicName: register-hostname-topic

Or does it suffice to just mention it as a function trigger?

Thanks!

1 Like

Defining them as an event source is sufficient to have them created. If you want your Lambdas to be able to publish to the topic then you need to grant the publish permission in the iamRoleStatements.

3 Likes

Thanks! I defs have some functions that need to publish, so your comment about iamRoleStatements is very useful.

So, a follow-up question about that. Is it possible to name an SNS topic, and then use that name inside a function that publishes to it? How would I describe that in the yaml file?

This probably requires a bigger write up but the short version is something like this:

provider:
  iamRoleStatements:
    - Effect: Allow
      Action:
        - SNS:Publish
      Resource: { "Fn::Join" : [":", ["arn:aws:sns:${self:custom.region}", { "Ref" : "AWS::AccountId" }, "${self:custom.snsTopic}" ] ]  }

custom:
  stage: ${opt:stage, self:provider.stage}
  region: ${opt:region, self:provider.region}
  snsTopic: "mytopic-${self:custom.stage}"

functions:
  myPublisherFunction:
    handler: publisher.handler
    environment:
      SNS_TOPIC_ARN: { "Fn::Join" : [":", ["arn:aws:sns:${self:custom.region}", { "Ref" : "AWS::AccountId" }, "${self:custom.snsTopic}" ] ]  }
  myReceiverFunction:
    handler: receiver.handler
    events:
      - sns: ${self:custom.snsTopic}

Then inside your publisher function you get the topic ARN from process.env.SNS_TOPIC_ARN if you’re using Node or the equivalent for other languages.

4 Likes

Thanks, mate! This should definitely get me on my way.