跨区域AWS Lambda向SNS发布消息可行吗?附代码及报错求助
AWS Lambda跨区域发布SNS消息问题解决
问题描述
我有一个部署在us-east-1区域的AWS Lambda函数,需要向us-east-1与eu-central-1两个区域的SNS Topic发布消息,请问这是否可行?看到boto3官方文档指出“只能向同一AWS区域内的Topic和终端节点发布消息”,这让我困惑,希望能实现跨区域发布。当SNS在不同区域时,代码抛出InvalidParameterException错误。
报错信息
{ "response": { "stackTrace": [ [ "/var/task/lambda_function.py", 28, "send_to_sns", "Message=message['body']" ], [ "/var/runtime/botocore/client.py", 357, "_api_call", "return self._make_api_call(operation_name, kwargs)" ], [ "/var/runtime/botocore/client.py", 676, "_make_api_call", "raise error_class(parsed_response, operation_name)" ] ], "errorType": "InvalidParameterException", "errorMessage": "An error occurred (InvalidParameter) when calling the Publish operation: Invalid parameter: TopicArn" } }
原代码
from __future__ import print_function import json import urllib import boto3 print('Loading message function...') def send_to_sns(message, context): # 该函数接收包含三个字段的JSON输入:SNS主题的ARN、消息主题字符串、消息内容字符串 # 随后将消息发送至指定SNS主题 # # 示例: # { # "topic": "arn:aws:sns:REGION:123456789012:MySNSTopic", # "subject": "这是消息的主题。", # "message": "这是消息的内容。" # } sns = boto3.client('sns') sns.publish( TopicArn=message['topic'], Subject=message['subject'], Message=message['body'] ) return ('已向Amazon SNS主题发送消息。')
解决方案
问题根源
默认创建的boto3 SNS客户端会使用Lambda所在区域(us-east-1)的服务端点,用这个客户端调用其他区域的SNS Topic时,会因端点不匹配触发InvalidParameterException错误。AWS服务的不同区域有独立的API端点,必须针对目标区域创建对应的客户端才能正常调用。
修改后的代码
from __future__ import print_function import json import boto3 print('Loading message function...') def send_to_sns(message, context): # 从Topic ARN中提取目标区域(ARN格式:arn:aws:sns:REGION:ACCOUNT_ID:TOPIC_NAME) topic_arn = message['topic'] target_region = topic_arn.split(':')[3] # 创建对应区域的SNS客户端 sns = boto3.client('sns', region_name=target_region) sns.publish( TopicArn=topic_arn, Subject=message['subject'], Message=message['body'] ) return ('已向Amazon SNS主题发送消息。')
说明
- 从Topic ARN中自动提取目标区域,无需硬编码,适配任意区域的SNS Topic
- 通过指定
region_name参数,让boto3客户端连接到目标区域的SNS服务端点,实现跨区域消息发布 - 该方法支持同时向多个不同区域的Topic发送消息,只需依次处理每个Topic的ARN即可
内容的提问来源于stack exchange,提问作者Kashif Mohammed
相关产品推荐
相关产品推荐

