sam templateyaml
Sam template.yaml – A Practical Playbook
Key Takeaways
- Understand the core sections of a
template.yamlfile and how they map to AWS resources. - Use built‑in SAM transforms to simplify Lambda, API Gateway, DynamoDB, and more.
- Validate early with
sam validateand automated linting. - Leverage parameters, conditions, and macros for reusable, environment‑agnostic templates.
- Deploy confidently using
sam deploy --guidedor CI/CD pipelines.
Why template.yaml Matters
The template.yaml file is the heart of an AWS Serverless Application Model (SAM) project. It is a superset of AWS CloudFormation that lets you declare serverless resources in a concise, declarative format. Mastering this file unlocks faster iteration, reproducible environments, and cost‑effective infrastructure as code.
Core Structure of a SAM template.yaml
Minimal Viable Template
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Simple Hello World Lambda
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.11
Handler: app.lambda_handler
CodeUri: src/
Events:
HttpGet:
Type: Api
Properties:
Path: /hello
Method: get
Key Sections Explained
- Transform – Informs CloudFormation to treat the file as a SAM template.
- Globals – Optional defaults applied to all resources of a given type.
- Parameters – Input values that make the template portable across accounts and stages.
- Resources – The actual AWS resources (Lambda, API, DynamoDB, etc.).
- Outputs – Values you want to expose after deployment (e.g., API endpoint URL).
Playbook Checklist: From Draft to Production
- Initialize Project
- Run
sam init --runtime python3.11 --name my-app. - Commit the generated
template.yamlto version control.
- Run
- Define Parameters & Globals
- Use
Parametersfor environment‑specific values (e.g.,Stage,TableName). - Set common runtime, timeout, and memory in
Globals.
- Use
- Model Resources
- Prefer
AWS::Serverless::Functionover rawAWS::Lambda::Function. - Attach API events with
AWS::Serverless::Apifor automatic Swagger generation. - Leverage
AWS::Serverless::SimpleTablefor quick DynamoDB prototypes.
- Prefer
- Validate & Lint
- Run
sam validateafter each edit. - Integrate
cfn-lintorsam lintin CI pipelines.
- Run
- Package & Deploy
- Package artifacts:
sam package --output-template-file packaged.yaml --s3-bucket my-bucket. - Deploy with guided mode the first time:
sam deploy --guided. - Store the generated
samconfig.tomlfor repeatable deployments.
- Package artifacts:
- Monitor & Iterate
- Enable
TracingandLogsin function properties. - Set up CloudWatch Alarms for error rates and throttles.
- Use
sam syncfor rapid local‑to‑cloud iteration.
- Enable
Comparison: SAM template.yaml vs. CloudFormation vs. Serverless Framework
| Feature | AWS SAM (template.yaml) |
AWS CloudFormation (.yaml/.json) |
Serverless Framework (serverless.yml) |
|---|---|---|---|
| Primary Use‑Case | Serverless‑first, Lambda + API Gateway | General‑purpose IaC (all AWS services) | Multi‑cloud serverless orchestration |
| Built‑in Transform | AWS::Serverless-2016-10-31 |
None (native CFN) | None (custom plugins) |
| Resource Shorthand | Yes (e.g., AWS::Serverless::Function) |
No (full AWS::Lambda::Function syntax) |
Yes (via functions block) |
| Local Testing | sam local invoke, sam local start-api |
Requires third‑party tools (e.g., LocalStack) | sls invoke local, sls offline |
| CI/CD Integration | Native sam deploy, CloudFormation StackSets |
CloudFormation Change Sets, CodePipeline | Serverless Deploy Plugin, CI plugins |
| Parameter Management | CFN Parameters + samconfig.toml |
CFN Parameters + SSM/Secrets Manager | Variables, --stage flags, external config files |
| Learning Curve | Low for Lambda‑centric apps | Medium‑high (full CFN spec) | Medium (YAML + plugin ecosystem) |
Advanced Patterns to Elevate Your template.yaml
1. Conditional Resources for Multi‑Stage Deployments
Parameters:
Stage:
Type: String
AllowedValues: [dev, prod]
Conditions:
IsProd: !Equals [!Ref Stage, prod]
Resources:
ProdOnlyTable:
Type: AWS::Serverless::SimpleTable
Condition: IsProd
Properties:
PrimaryKey:
Name: id
Type: String
2. Macro‑Driven Reuse (AWS::Include)
Store common IAM policies in a separate file and inject them with !Include to avoid duplication.
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Policies: !Include policies/common-policies.yaml
3. Nested Stacks for Large Applications
Break a monolithic template.yaml into feature‑specific nested stacks to improve readability and parallel deployment.
Resources:
AuthStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: ./auth/template.yaml
Parameters:
Stage: !Ref Stage
Frequently Asked Questions
- What is the difference between
AWS::Serverless::FunctionandAWS::Lambda::Function? AWS::Serverless::Functionis a SAM shorthand that automatically creates an execution role, adds permission for API Gateway, and supportsEventsmapping.AWS::Lambda::Functionrequires you to define those resources manually.- Can I use
template.yamlto provision non‑serverless resources? - Yes. Since SAM is built on top of CloudFormation, you can include any standard CloudFormation resource (e.g.,
AWS::S3::Bucket,AWS::DynamoDB::Table) alongside serverless resources. - How do I keep secret values out of
template.yaml? - Reference secrets stored in AWS Secrets Manager or Parameter Store using the
!Refor!Subintrinsic functions, and grant the Lambda execution role permission to read them.