咨询SAM Local是否支持创建SNS Topic及相关配置方式
Great question! The good news is that SAM Local absolutely supports creating SNS Topics directly via your SAM template—you don’t have to rely on pre-existing topics at all. This is one of the core strengths of using SAM: it lets you define all your serverless resources (including SNS Topics, Lambda functions, subscriptions, etc.) in a single template, and both full AWS deployments and local testing workflows will respect those definitions.
Here’s a concrete example of how to set this up in your SAM template:
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: SAM Template with SNS Topic and Lambda Subscriber Resources: # Define your SNS Topic directly in the template MyCustomSNSTopic: Type: AWS::SNS::Topic Properties: DisplayName: "My Local Test Topic" TopicName: "MyLocalTestTopic" # Lambda function that subscribes to the SNS Topic MySNSTriggeredLambda: Type: AWS::Serverless::Function Properties: CodeUri: ./src/ Handler: app.lambdaHandler Runtime: nodejs18.x Events: SNSTrigger: Type: SNS Properties: Topic: !Ref MyCustomSNSTopic FilterPolicy: eventType: - "order_placed"
When you use SAM Local to test this setup (for example, running sam local invoke MySNSTriggeredLambda with a mock SNS event), SAM Local will simulate the existence of the topic you defined. You don’t need to create anything manually in AWS first—everything is handled locally based on your template’s resource definitions.
If you want to test the full end-to-end flow (publishing to the topic and seeing the Lambda trigger), you can use the AWS CLI to publish to SAM Local’s mock SNS endpoint (provided when running local services) or leverage SAM’s built-in event generation tools.
To recap: you absolutely can have SAM Local create the SNS Topic for you via your template—no need to depend on pre-existing resources. This aligns with the infrastructure-as-code approach SAM is built for, making your local testing environment mirror your production setup as closely as possible.
内容的提问来源于stack exchange,提问作者red888

