Cloud Unfold

unfolding the cloud trivia

LambdaSNS

Cross Account Lambda Subscription for SNS Topic

As the name suggests, SNS is truly a simple notification service, however when trying to add a cross account Lambda function as a subscription for SNS topic, we need to perform additional steps. In this quick article, we will see how to configure a cross account Lambda function as a subscription for an SNS topic.

To perform cross account SNS message deliveries to a Lambda function, we need to:

  • authorize cross account Lambda to be invoked by SNS
  • SNS needs to allow Lambda to make subscribe request. Additional permissions like receive, ListSubscriptionsByTopic, etc. can be added if required
  • subscribe the Lambda function to the SNS topic

As not all these options available through the AWS Console, we need to use AWS CLI.

  1. Create an SNS topic, if you already have one, you can skip to the next step
    $ aws sns create-topic --name cross-account-lambda-test
  2. Create a Lambda function, if you already have one, you can skip to the next step
    $ aws lambda create-function \
         --function-name "SNS-cross-account-Test-Function" \
         --runtime python3.8 \
         --role <lambda-function-exexution-role-arn> \
         --handler index.handler \
         --description "SNS cross account Test Function" \
         --timeout 60 \
         --memory-size 128 \
         --zip-file fileb:///$PATH/my-deployment-package.zip
    
  3. In the SNS account, allow Lambda function to make Subscribe request to the topic
    $ aws sns add-permission \
         --region <region> \
         --topic-arn <sns-topic-arn> \
         --label cross-account-lambda-access \
         --aws-account-id <Lambda-account-Id> \
         --action-name Subscribe Receive ListSubscriptionsByTopic
    
  4. From Lambda account, make a subscription request i.e. subscribe Lambda to the SNS Topic
    $ aws sns subscribe \
         --topic-arn <sns-topic-arn> \
         --protocol lambda \
         --notification-endpoint <Lambda-function-arn>
    
  5. In Lambda function, allow SNS topic to invoke the Lambda function
    $ aws lambda add-permission \
         --function-name SNS-cross-account-Test-Function \
         --statement-id "SNS-cross-account-Test-Function" \
         --action "lambda:InvokeFunction" \
         --principal sns.amazonaws.com \
         --source-arn <sns-topic-arn>
    
  6. Test the subscription
    $ aws sns publish \
         --topic-arn <sns-topic-arn> \
         --message '{ "Message": "Hello World" }' \
         --subject Test
    

These steps also work for the SNS topic and Lambda function in the same account, however its pretty easy to configure that from the console. For cross account, the above steps should help. Cheers!

Was it helpful?

Just another lazy guy

LEAVE A RESPONSE

Your email address will not be published. Required fields are marked *

Related Posts