# Subscribing a Lambda to an SNS Topic in a Different Account We have a scenario where one account, SNS_account, contains some SNS topics. A different account, Lambda_account, contains a Lambda function. We want SNS to invoke the Lambda function directly even though they are in different accounts. ![[lambda_and_sns_across_accounts.png]] First we need to give SNS permission to add permissions in the Lambda_account in order to connect the SNS subscription to the Lambda function. Second we need to subscribe the Lambda to the SNS topic from the Lambda_account. ```bash aws sns add-permission --label lambda-access --aws-account-id <Lambda_account_id> \ --topic-arn arn:aws:sns:us-east-2:<SNS_account_id>:<SNS_topic> \ --action-name Subscribe ListSubscriptionsByTopic --profile <SNS_profile> ``` ```bash aws sns subscribe --protocol lambda \ --topic-arn arn:aws:sns:us-east-2:<SNS_account_id>:<SNS_topic> \ --notification-endpoint arn:aws:lambda:us-east-2:<Lambda_account_id>:function:<Lambda_name> \ --profile <Lambda_profile> ``` ### Legend - SNS_topic: the SNS topic name (such as "location-updates"). - Lambda_name: the Lambda function name (such as "process-location-updates"). - SNS_account_id: the 11-digit account number of the account in which the SNS topic exists. - SNS_profile: the local profile of the user in the SNS_account. - Lambda_account_id: the 11-digit account number of the account in which the Lambda function exists. - Lambda_profile: the local profile of the user in the Lambda_account. # Caveats In our environment we are currently deploying apps mostly with Terraform. With Terraform, when you deploy (`terraform apply`) then Terraform will see that the SNS topic has an extra subscription and will remove the subscription. If you are using CloudFormation then you are introducing drift into your environment. The changes will cause CloudFormation to fail and rollback future CloudFormation updates unless you remove the subscriptions. # References - [AWS Lambda Developer Guide with SNS Examples](https://docs.aws.amazon.com/lambda/latest/dg/with-sns-example.html) --- Created: 2022-12-09 08:39