How to trigger Lambda with SNS (part II)

Hey,

Last time I talked about Lambda and SNS here in How to trigger Lambda with SNS. The great thing with Lambda is that it's brought with Serverless. Serverless has a configuration file serverless.yml where you can configure absolutely everything concerning your Lambda (env variables, plugins, iam roles, aws resources access, event, runtime, timeout etc..)

Configure and deploy easily

The thing behind serverless.yml is that your configuration file will drastically change the way you are currently deploying applications. Actually you'll not have to double check all of your attached events between services, they will be properly connected. Otherwise you'll have to go to your Lambda and manually link your data according to the specified resource/service.

There is a documentation that shows you how to attach event directly from your serverless.yml file.

However when I worked with SNS it did not work as expected. Unfortunately, I realize that Serverless was poorly documented or outdated for some part of it . I did find multiple way of doing it but as a result my Lambda was not deployed or not properly SNS attached.

See the following options:

- sns:
    topicName: topic_name
    displayName: topic_display_name

OR

- sns: arn:aws:sns:xxxx:xxxx:xxxx

OR

- sns: arn:aws:sns:xxxx:xxxx:xxxx

I figured it out also that I was no the only one facing those kind of issues, see this and this but I managed to sort this out with a wonderful plugin:

serverless-plugin-external-sns-events

I am also using serverless-plugin-external-sns-events from the same repo see silvermine

So the external-sns-events helps you to check all of your attached event and make sure they will be well attached each time your Lambda is deployed.

Just add serverless-plugin-external-sns-events as plugin into serverless.yml

plugins:
- serverless-plugin-external-sns-events

Once this is done, this is how you can attach SNS event to a Lambda:

functions:
  your_function_name:
    description: description
    handler: your_function_handler
    events:
      - externalSNS: first_SNS_topicName
      - externalSNS: second_SNS_topicName

Plugin will subscribe/unsubscribe for you if needed.

In this way you are ready to go to deploy and attach on the fly your Lambda across your services with SNS.

That's all for today, hope it helps you to understand Lambda and SNS and especially the way you can attach a SNS topic through your Serverless configuration's file.