能否在Serverless.yml中使用AWS CloudFormation的Mappings段?
Absolutely—you can include CloudFormation-style Mappings sections in your serverless.yml file, but you need to place them correctly and fix a small YAML formatting issue in your example first.
First, Fix the YAML Syntax
Your sample Mappings has a minor formatting problem: YAML requires a space after the colon in key-value pairs. So instead of 56565d644801:true, it should be 56565d644801: true. This might seem trivial, but it’ll cause parsing errors if omitted.
Correct Placement in serverless.yml
Serverless Framework converts your serverless.yml into a CloudFormation template under the hood, so it supports embedding native CloudFormation top-level elements like Mappings—but you need to nest them under the resources block, alongside Resources (if you have any custom CloudFormation resources).
Here’s your corrected example:
service: my-example-service functions: MyFunction: handler: src/MyFunction/func.lambda_handler role: MyRole events: - schedule: rate: rate(12 hours) enabled: Fn::FindInMap: - accounts - !Ref AWS::AccountId resources: Mappings: accounts: 56565d644801: true 986958470041: true 090960219037: true 05166767667: false
How It Works
When you deploy or package your service, Serverless will inject the Mappings block directly into the generated CloudFormation template. The Fn::FindInMap (or its shorthand !FindInMap) will then correctly look up whether the schedule should be enabled based on your current AWS account ID.
Quick Validation Tip
To confirm everything is set up correctly, run serverless package and check the generated template at .serverless/cloudformation-template-update-stack.json. You’ll see your Mappings included at the top level, and the enabled field for your schedule will reference it properly.
Just make sure you’re using a modern version of Serverless Framework—older versions might have limited support for native CloudFormation elements, but all recent releases handle this seamlessly.
内容的提问来源于stack exchange,提问作者José Enrique Hernández

