Tutorial: Using AWS Lambda with Amazon Simple Notification Service

You can use a Lambda function in one AWS account to subscribe to an Amazon SNS topic
in a separate AWS account. In
this tutorial, you use the AWS Command Line Interface to perform AWS Lambda operations
such as creating a Lambda function, creating an
Amazon SNS topic and granting permissions to allow these two resources to access each
other.

Prerequisites

This tutorial assumes that you have some knowledge of basic Lambda operations and
the Lambda console. If you
haven't already, follow the instructions in Getting started with AWS Lambda to create your first Lambda function.

To follow the procedures in this guide, you will need a command line terminal or shell
to run commands. Commands are shown in
listings preceded by a
prompt symbol ($) and the name of the current directory, when appropriate:

~/lambda-project$ this is a command
this is output

For long commands, an escape character (\) is used to split a command over multiple lines.

In the tutorial, you use two accounts. The AWS CLI commands illustrate this by using
two named profiles, each configured for use with a different
account. If you use profiles with different names, or the default profile and one
named profile, modify the
commands as needed.

Create an Amazon SNS topic

From account A, create the source Amazon SNS topic.

$ aws sns create-topic --name lambda-x-account --profile accountA

Note the topic ARN that is returned by the command. You will need it when you add
permissions to the Lambda
function to subscribe to the topic.

Create the execution role

From account B, create the execution role that gives your
function permission to access AWS resources.

The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to
write logs to CloudWatch Logs.

Create a Lambda function

From account B, create the function that processes events from Amazon SNS. The following
example code receives an
Amazon SNS event input and processes the messages that it contains. For illustration,
the code writes some of the
incoming event data to CloudWatch Logs.

Do not use the --source-account parameter to add a source account to the Lambda policy when adding
the policy. Source account is not supported for Amazon SNS event sources and will
result in access being denied.

Create a subscription

From account B, subscribe the Lambda function to the topic. When a message is sent
to the
lambda-x-account topic in account A, Amazon SNS invokes the SNS-X-Account function in
account B.

This will return a message id with a unique identifier, indicating the message has
been accepted by the Amazon SNS
service. Amazon SNS will then attempt to deliver it to the topic's subscribers. Alternatively,
you could supply a JSON
string directly to the message parameter, but using a text file allows for line breaks in the
message.