# Send an SNS notification using AWS Lambda

Welcome! Today, I am going to show you how to write an AWS Lambda Function that sends an SNS notification. 

🐦 Follow me on [Twitter](https://twitter.com/ninan_phillip) if you would like to see more content like this! 🐦

TLDR - Here is a link to my [Github](https://github.com/fourgates/blog-lambda-sns-demo) with the given code.

## 1. Initialize the Project
> You can follow my [previous post](https://blog.phillipninan.com/deploy-a-lambda-function-using-aws-sam-in-5-minutes) on how to use [AWS SAM](https://aws.amazon.com/serverless/sam/) to spin up a boilerplate Lambda function. 

## 2. Email
> First, let's write a function to send an email and return a promise. 
```
function sendEmail(message){
    const awsRegion = "us-east-1";
    // FIXME - update this ARN
    const snsTopic = 'arn:aws:sns:us-east-1:12341234-ABCDABCD';
    const snsSubject = 'SNS Subject';
    // Create publish parameters
    var params = {
      Message: message,
      Subject: snsSubject,
      TopicArn: snsTopic
    };
    var sns = new AWS.SNS({ region: awsRegion });
    return sns.publish(params).promise();
}
```

## 3. Next, we bring it all together in the handler. 
```
const AWS = require("aws-sdk");    

/**
 * A Lambda function that sends an SNS message
 */
exports.handler = (event, context) => {
    let message = "Hello from Lambda!";
    return sendEmail(msg).then((err,data)=>{
        console.log ("We are in the callback!");
        if (err) {
            console.log('Error sending a message', err);
            context.fail(err);
        } else {
            console.log('Sent message:', data.MessageId);
            context.succeed("Done!");
        }      
    });
};
...
...
```

## 4. Add an SNS Role
> You will need to add a policy for this Lambda to be able to properly send SNS messages. We need to make a small update to the CloudFormation template to make use of this. If you did not use AWS SAM to generate the project, you can simply update the assigned role using the AWS Console.
```
  snsLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/index.handler
      Runtime: nodejs12.x
      MemorySize: 128
      Timeout: 100
      Description: A Lambda function sends an SNS notification.
      Policies:
        # Give Lambda basic execution Permission to the helloFromLambda
        - AWSLambdaBasicExecutionRole
        # This is the new policy
        - AmazonSNSFullAccess
```
TLDR - Here is a link to my [Github](https://github.com/fourgates/blog-lambda-sns-demo) with the given code.

🐦 Follow me on [Twitter](https://twitter.com/ninan_phillip) if you would like to see more content like this! 🐦

## Conclusion
That's it! In a couple of dozen lines of code, you can easily utilize SNS subscriptions to send notifications.
