I want to subscribe a private HTTP or HTTPS endpoint to my Amazon Simple Notification Service (Amazon SNS) topic.
Resolution
To subscribe a private HTTP or HTTPS endpoint to an Amazon SNS topic, complete the following steps.
Create an Amazon VPC security group LambdaSG in the same Amazon VPC as the private endpoint
- Open the Amazon VPC console.
- In the navigation pane, under Security, choose Security groups. Then, choose Create security group.
- For Security group name, enter LambdaSG.
- For VPC, choose the Amazon virtual private cloud (VPC) that the private endpoint is in.
- Choose Create security group.
Create a Lambda function inside the same Amazon VPC and subnet as the private endpoint and configure it with the LambdaSG security group
- Open the Lambda console.
- Choose Create function.
- Choose Author from scratch.
- For Function name, enter a name that describes the purpose of your function. For example, Private-endpoint-Amazon-SNS-topic-subscription.
- For Runtime, choose Python 3.12.
- Choose Additional configurations. Then, choose Enable VPC.
- For the VPC, choose the subnet that the private endpoint is in.
- Choose Create function.
Edit the private endpoint's security group rules to allow inbound connection from the Lambda function's security group
- Open the Amazon VPC console.
- In the navigation pane, under Security, choose Security groups.
- In Security groups, choose the private endpoint's security group.
- Choose Edit inbound rules.
- For Type, choose HTTP or HTTPS. The Protocol and Port range fields are populated automatically.
- For Source, choose Custom. Then, choose the LambdaSG security group.
- Choose Save rules.
Configure the Lambda function to pass incoming Amazon SNS notifications to the private endpoint
- Open the Lambda console.
- In the navigation pane, choose Functions.
- In Function name, choose the function that you created previously.
- In Code source, replace the default code with the following code:
from __future__ import print_function
import json
import urllib3
http = urllib3.PoolManager()
def lambda_handler(event, context):
url = "PRIVATE_HTTP/S_ENDPOINT_URL"
sns_message_payload = event["Records"][0]["Sns"]
sns_message_headers = {
"x-amz-sns-message-id": sns_message_payload['MessageId'],
"x-amz-sns-message-type": sns_message_payload["Type"],
"x-amz-sns-subscription-arn" : event["Records"][0]["EventSubscriptionArn"],
"x-amz-sns-topic-arn" : sns_message_payload["TopicArn"]
}
try:
r = http.request('POST', url, headers=sns_message_headers, body=json.dumps(sns_message_payload))
print(r.data)
except Exception as e:
print(e)
Important: Replace the url value with the URL of your private endpoint.
- Choose Deploy.
Subscribe the Lambda function to your Amazon SNS topic
For more information, see Tutorial: Using Lambda with Amazon SNS.