Sending SMS using AWS Simple Notification Service

Sending SMS using AWS Simple Notification Service

Overview

This article will show you how to use AWS Simple Notification Service (SNS) with Notivize.

In order to track notification deliveries properly there are a few manual steps that you'll need to take, but they are pretty easy and we'll walk through them step by step.

You'll need an IAM user with the correct permissions to get started.

AWS IAM User

In order for us to be able to create the required resources for sending SMS notifications via SNS and tracking delivery metrics, we will need an AWS access key id and secret key with the following permissions:

  1. AmazonSNSFullAccess
🔒 List of permissions

The reason we ask for full access on SNS is to make sure we can create the required resources to send SMSes, verify your configuration and track delivery data. It also means we won't have to ask you to change your permissions in the future if we add more features to our integration with SNS.

However, we understand that security is important and you may want to limit the permissions to the strict minimum. Here is the exact list:

  • Comment: Deny publishing to topics
    Effect: Deny
    Action:
    • "sns: Publish"
    Resource:
    • "arn:aws:sns:*:*:*"
  • Comment: Allow publishing to sms and other required actions. Effect: Allow
    Action:
    • sns:CreateTopic
    • sns:Publish
    • sns:Subscribe
    Resource:
    • "*"

SNS delivery metrics tracking

Setup SNS delivery status logs

  1. Login into your AWS account
  2. Go to the SNS console: https://console.aws.amazon.com/sns/v3/home#/dashboard
  3. Click on "Text Messaging (SMS)"
AWS SNS Console - Text Messaging (SMS)AWS SNS Console - Text Messaging (SMS)

AWS SNS Console - Text Messaging (SMS)

  1. Scroll down and click on "Edit Preferences"
AWS SNS Console - Edit PreferencesAWS SNS Console - Edit Preferences

AWS SNS Console - Edit Preferences

  1. Expand the "Delivery Status logging" panel, select "Create new service role", and then click on "Create new roles"
AWS SNS Console - Create new rolesAWS SNS Console - Create new roles

AWS SNS Console - Create new roles

  1. In the new tab, keep the default values and click on "Allow"
AWS SNS Console - Create new roles tabAWS SNS Console - Create new roles tab

AWS SNS Console - Create new roles tab

  1. Close the tab
  2. The new role ARN will be populated and you can click on "Save changes"
AWS SNS Console - Save changesAWS SNS Console - Save changes

AWS SNS Console - Save changes

Create Cloudwatch Log Group

📘

Pre-requesite

You must have purchased an origination number that has SMS capabilities.

See details at https://docs.aws.amazon.com/sns/latest/dg/channels-sms-originating-identities-origination-numbers.html

  1. Go to the SNS console
  2. Click on "Origination numbers" and copy the number you will be using to send a test text message
AWS SNS Console - Origination numbersAWS SNS Console - Origination numbers

AWS SNS Console - Origination numbers

  1. Click on "Text messaging (SMS)" in the sidebar and click "Publish new message"
AWS SNS Console - Publish text messageAWS SNS Console - Publish text message

AWS SNS Console - Publish text message

  1. Fill in the required fields and click "Publish message"
  1. Go to the Cloudwatch console and click on "Log groups" in the side nav to check that the log group has been created (the name should be similar to the one in the screenshot)
AWS Cloudwatch Console - Log groupsAWS Cloudwatch Console - Log groups

AWS Cloudwatch Console - Log groups

Integrate with Notivize

  1. Go to https://home.notivize.com
  2. Sign in into your account
  3. Go to "Settings"
  4. Click on "Link Account" from the SNS card
Amazon SES IntegrationAmazon SES Integration

Amazon SES Integration

SNS integration cardSNS integration card

SNS integration card

  1. Give the service a name you can remember easily. Use the IAM user credentials to fill in AWS ACCESS KEY ID and AWS SECRET ACCESS KEY, and set Region Name to the region you want to publish SMSes from.
  2. Click Link SNS Account
Amazon SNS integration - SuccessAmazon SNS integration - Success

Amazon SNS integration - Success

You have now successfully linked your SNS account with Notivize! 🎉 You are good to go and now you can select it as a service when creating/editing notifications. ✨
Don't stop here though, make sure you go through the next section (it's short, we promise!) to be able to track your delivery metrics in Notivize.

❗️

Integration Failure

If you get an error or the status of your integration shows "Inactive", make sure you have given your IAM user the correct permissions and try again.
You can also contact us at [email protected], we'd be happy to help!

Forward delivery metrics to Notivize

Create a Lambda function

In order for Notivize to be able to track your delivery metrics properly, you will need to create a lambda function that parses the SNS cloudwatch logs and forwards the interesting parts.

  1. Log in into your AWS account
  2. Go to the Lambda console: https://console.aws.amazon.com/lambda/home#/functions
  3. Click "Create function"
AWS Lambda Console - Create functionAWS Lambda Console - Create function

AWS Lambda Console - Create function

  1. Select "Author from scratch", give it a useful name (e.g. forward-sns-metrics-to-notivize)
  2. Choose "Python 3.8" as Runtime
  3. Click "Create Function"
AWS Lambda Console - Create functionAWS Lambda Console - Create function

AWS Lambda Console - Create function

  1. In the file lambda_function.py, copy/paste the following code:
import base64
import gzip
import json
import logging

import urllib3


NOTIVIZE_URL = "https://messaging-api.notivize.com/aws/sns/outcomes"


def lambda_handler(event, context):
    results = []

    # Extracting data from logs
    log_data = base64.b64decode(event["awslogs"]["data"])
    log_data = gzip.decompress(log_data)
    log_data = json.loads(log_data)

    http = urllib3.PoolManager()
    
    for record in log_data["logEvents"]:
        message = json.loads(record["message"])
        logging.debug(message)
        body = json.dumps({
          "eventType": "ExternalSMSSNS",
          "messageId": message["notification"]["messageId"],
          "status": line["status"],
        })
        response = http.request("POST", NOTIVIZE_URL, body=body)
        logging.debug(f"{response.status} {response.data}")
  1. Save the file and click "Deploy"
AWS Lambda Console - DeployAWS Lambda Console - Deploy

AWS Lambda Console - Deploy

Connect the Cloudwatch logs to the Lambda function

  1. Go to the Cloudwatch console and click on "Log groups"
  2. Search for the log group ending with "DirectPublishToPhoneNumber" and click on it
  3. Click on the "Subscription Filters" tab
  4. Click on Create and select "Create Lambda Subscription filter"
AWS CloudWatch Console - Create Lambda subscription filterAWS CloudWatch Console - Create Lambda subscription filter

AWS CloudWatch Console - Create Lambda subscription filter

  1. Select the lambda function we previously created as the destination
  2. Give a name to your subscription (e.g. forward-logs-to-notivize)
  3. Click on "Start Streaming"

❗️

Additional Costs

Note: you'll be charged for the lambda usage. Unfortunately, this is the only way currently to be able to forward delivery information from SNS.


Did this page help you?