
Aws Cloudformation Lambda
- 71 installs
- 318 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit
Author AWS CloudFormation templates for Lambda functions, layers, and event sources like API Gateway, SQS, SNS, and EventBridge.
About
Provides CloudFormation patterns for Lambda serverless infrastructure including functions, layers, event sources, and API Gateway/Step Functions integrations. A developer uses it to provision serverless workloads as code with cold-start optimization.
- Layers for shared code and triggers from API Gateway, SQS, SNS, EventBridge
- Cold-start optimization and cross-stack reference patterns
Aws Cloudformation Lambda by the numbers
- 71 all-time installs (skills.sh)
- Ranked #648 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill aws-cloudformation-lambdaAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 71 |
|---|---|
| repo stars | ★ 318 |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit ↗ |
What it does
Author AWS CloudFormation templates for Lambda functions, layers, and event sources like API Gateway, SQS, SNS, and EventBridge.
Files
AWS CloudFormation Lambda Serverless
Overview
Create production-ready serverless infrastructure using AWS CloudFormation templates. This skill covers Lambda functions, layers, event sources, API Gateway, Step Functions, cold start optimization, and best practices for parameters, outputs, and cross-stack references.
When to Use
Use this skill when:
- Creating new Lambda functions with CloudFormation
- Configuring Lambda layers for shared code
- Integrating Lambda with API Gateway (REST and HTTP API)
- Implementing event sources (SQS, SNS, EventBridge, S3, DynamoDB)
- Creating Step Functions with Lambda workflows
- Optimizing cold start and performance
- Organizing templates with Parameters, Outputs, Mappings, Conditions
- Implementing cross-stack references with export/import
- Using Transform for macros and reuse
CloudFormation Template Structure
Base Template with Standard Format
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with API Gateway integration
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Function Configuration
Parameters:
- FunctionName
- Runtime
- Handler
- Label:
default: Deployment Settings
Parameters:
- Environment
- DeployStage
Parameters:
FunctionName:
Type: String
Default: my-lambda-function
Description: Name of the Lambda function
Runtime:
Type: String
Default: python3.11
AllowedValues:
- python3.8
- python3.9
- python3.10
- python3.11
- nodejs18.x
- nodejs20.x
- java11
- java17
- java21
Handler:
Type: String
Default: index.handler
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
DeployStage:
Type: String
Default: dev
Mappings:
EnvironmentConfig:
dev:
MemorySize: 128
Timeout: 30
ReservedConcurrentExecutions: 5
staging:
MemorySize: 256
Timeout: 60
ReservedConcurrentExecutions: 20
production:
MemorySize: 512
Timeout: 120
ReservedConcurrentExecutions: 100
Conditions:
IsProduction: !Equals [!Ref Environment, production]
IsDev: !Equals [!Ref Environment, dev]
Transform:
- AWS::Serverless-2016-10-31
Resources:
# Lambda Function
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Ref FunctionName
Runtime: !Ref Runtime
Handler: !Ref Handler
Code:
S3Bucket: !Ref SourceBucket
S3Key: !Sub "lambda/${Environment}/function.zip"
MemorySize: !FindInMap [EnvironmentConfig, !Ref Environment, MemorySize]
Timeout: !FindInMap [EnvironmentConfig, !Ref Environment, Timeout]
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
LOG_LEVEL: !If [IsProduction, INFO, DEBUG]
Tags:
- Key: Environment
Value: !Ref Environment
- Key: Project
Value: !Ref ProjectName
Outputs:
LambdaFunctionArn:
Description: ARN of the Lambda function
Value: !GetAtt MyLambdaFunction.Arn
Export:
Name: !Sub "${AWS::StackName}-LambdaFunctionArn"Best Practices for Parameters
AWS-Specific Parameter Types
Parameters:
# AWS-specific types for validation
VPCId:
Type: AWS::EC2::VPC::Id
Description: VPC where Lambda will run
SubnetIds:
Type: List<AWS::EC2::Subnet::Id>
Description: Subnets for Lambda VPC config
SecurityGroupIds:
Type: List<AWS::EC2::SecurityGroup::Id>
Description: Security groups for Lambda
LambdaRuntime:
Type: AWS::Lambda::Runtime
Description: Lambda runtime selection
IAMRoleArn:
Type: AWS::IAM::Role::Arn
Description: IAM role for Lambda execution
S3BucketForCode:
Type: AWS::S3::Bucket
Description: S3 bucket for Lambda code
KMSKeyArn:
Type: AWS::KMS::Key::Arn
Description: KMS key for environment variablesParameter Constraints
Parameters:
FunctionName:
Type: String
Default: my-function
Description: Lambda function name
ConstraintDescription: Must be 1-64 characters, alphanumeric and hyphens
MinLength: 1
MaxLength: 64
AllowedPattern: "[a-zA-Z0-9-_]+"
MemorySize:
Type: Number
Default: 128
Description: Memory allocation in MB
MinValue: 128
MaxValue: 10240
ConstraintDescription: Must be between 128 and 10240 MB
Timeout:
Type: Number
Default: 30
Description: Function timeout in seconds
MinValue: 1
MaxValue: 900
ConstraintDescription: Must be between 1 and 900 seconds
EnvironmentName:
Type: String
Default: dev
Description: Deployment environment
AllowedValues:
- dev
- staging
- production
ConstraintDescription: Must be dev, staging, or productionSSM Parameter References
Parameters:
DatabaseConnectionString:
Type: AWS::SSM::Parameter::Value<String>
Default: /myapp/database/connection-string
Description: Database connection string from SSM
ApiKey:
Type: AWS::SSM::Parameter::Value<SecureString>
Default: /myapp/external-api/key
Description: API key from SSM Parameter StoreOutputs and Cross-Stack References
Export/Import Patterns
# Stack A - Network Stack
AWSTemplateFormatVersion: 2010-09-09
Description: Network infrastructure stack
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpc"
Outputs:
VPCId:
Description: VPC ID
Value: !Ref VPC
Export:
Name: !Sub "${AWS::StackName}-VPCId"
PublicSubnetIds:
Description: Public subnet IDs
Value: !Join [",", [!Ref PublicSubnet1, !Ref PublicSubnet2]]
Export:
Name: !Sub "${AWS::StackName}-PublicSubnetIds"
PrivateSubnetIds:
Description: Private subnet IDs
Value: !Join [",", [!Ref PrivateSubnet1, !Ref PrivateSubnet2]]
Export:
Name: !Sub "${AWS::StackName}-PrivateSubnetIds"
LambdaSecurityGroupId:
Description: Security group ID for Lambda
Value: !Ref LambdaSecurityGroup
Export:
Name: !Sub "${AWS::StackName}-LambdaSecurityGroupId"# Stack B - Application Stack (imports from Stack A)
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda application stack
Parameters:
NetworkStackName:
Type: String
Default: network-stack
Description: Name of the network stack
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-processor"
Runtime: python3.11
Handler: index.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
Role: !GetAtt LambdaExecutionRole.Arn
VpcConfig:
SecurityGroupIds:
- !ImportValue
!Sub "${NetworkStackName}-LambdaSecurityGroupId"
SubnetIds:
- !Select [0, !Split [",", !ImportValue !Sub "${NetworkStackName}-PrivateSubnetIds"]]
- !Select [1, !Split [",", !ImportValue !Sub "${NetworkStackName}-PrivateSubnetIds"]]Nested Stacks for Modularity
AWSTemplateFormatVersion: 2010-09-09
Description: Main stack with nested Lambda stacks
Resources:
# Nested stack for Lambda functions
LambdaFunctionsStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/bucket/lambda-functions.yaml
TimeoutInMinutes: 15
Parameters:
Environment: !Ref Environment
FunctionNamePrefix: !Ref FunctionNamePrefix
# Nested stack for API Gateway
ApiGatewayStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/bucket/api-gateway.yaml
TimeoutInMinutes: 15
Parameters:
Environment: !Ref Environment
LambdaFunctionArn: !GetAtt LambdaFunctionsStack.Outputs.FunctionArnLambda Functions with Advanced Configurations
Lambda Base with VPC and Environment
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with VPC, environment variables, and monitoring
Parameters:
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
VpcConfig:
Type: String
Default: full
AllowedValues:
- none
- full
- internal
Resources:
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-lambda-role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: !Sub "${AWS::StackName}-vpc-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- ec2:CreateNetworkInterface
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
Resource: "*"
- PolicyName: !Sub "${AWS::StackName}-secrets-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource: !Ref SecretsArn
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-processor"
Runtime: python3.11
Handler: index.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: !Sub "lambda/${Environment}/function.zip"
MemorySize: 256
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
VpcConfig:
!If
- IsFullVpc
- SecurityGroupIds:
- !Ref LambdaSecurityGroup
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref AWS::NoValue
Environment:
Variables:
ENVIRONMENT: !Ref Environment
LOG_LEVEL: !If [IsProduction, INFO, DEBUG]
DB_HOST: !Ref DatabaseHost
DB_NAME: !Ref DatabaseName
TracingConfig:
Mode: !If [IsProduction, Active, PassThrough]
Tags:
- Key: Environment
Value: !Ref Environment
- Key: Project
Value: !Ref ProjectName
- Key: CostCenter
Value: !Ref CostCenter
LambdaFunctionUrl:
Type: AWS::Lambda::Url
Properties:
AuthType: AWS_IAM
TargetFunctionArn: !GetAtt MyLambdaFunction.Arn
Cors:
AllowCredentials: true
AllowHeaders:
- "*"
AllowMethods:
- GET
- POST
AllowOrigins:
- !If [IsProduction, !Ref ProductionCorsOrigin, "*"]
MaxAge: 86400
Conditions:
IsFullVpc: !Equals [!Ref VpcConfig, full]
IsProduction: !Equals [!Ref Environment, production]Lambda with Provisioned Concurrency
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-api"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/api.zip
MemorySize: 512
Timeout: 30
Role: !GetAtt LambdaExecutionRole.Arn
ProvisionedConcurrencyConfig:
Type: AWS::Lambda::ProvisionedConcurrencyConfig
Properties:
FunctionName: !Ref MyLambdaFunction
ProvisionedConcurrentExecutions: 5
ProvisionedExecutionTarget:
AllocationStrategy: PRICE_OPTIMIZEDLambda Layers
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with layers
Resources:
CommonLibraryLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-common-lib"
Description: Common utilities for Lambda functions
Content:
S3Bucket: !Ref LayersBucket
S3Key: layers/common-lib.zip
CompatibleRuntimes:
- python3.9
- python3.10
- python3.11
CompatibleArchitectures:
- x86_64
- arm64
DataProcessingLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-data-processing"
Description: Data processing utilities
Content:
S3Bucket: !Ref LayersBucket
S3Key: layers/data-processing.zip
CompatibleRuntimes:
- python3.11
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-processor"
Runtime: python3.11
Handler: index.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/processor.zip
Layers:
- !Ref CommonLibraryLayer
- !Ref DataProcessingLayerAPI Gateway Integration
API Gateway REST with Lambda Proxy
AWSTemplateFormatVersion: 2010-09-09
Description: API Gateway REST with Lambda proxy integration
Resources:
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: !Sub "${AWS::StackName}-api"
Description: REST API for Lambda backend
EndpointConfiguration:
Types:
- REGIONAL
MinimumCompressionSize: 1024
DisableExecuteApiEndpoint: false
ApiGatewayResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref ApiGatewayRestApi
ParentId: !GetAtt ApiGatewayRestApi.RootResourceId
PathPart: items
ApiGatewayMethod:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref ApiGatewayRestApi
ResourceId: !Ref ApiGatewayResource
HttpMethod: GET
AuthorizationType: COGNITO_USER_POOLS
AuthorizerId: !Ref ApiGatewayAuthorizer
RequestParameters:
method.request.querystring.id: true
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations"
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
method.response.header.Content-Type: "'application/json'"
PassthroughBehavior: WHEN_NO_MATCH
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: Empty
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
ApiGatewayDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn: ApiGatewayMethod
Properties:
RestApiId: !Ref ApiGatewayRestApi
StageName: !Ref DeployStage
StageDescription:
LoggingLevel: !If [IsProduction, INFO, ERROR]
DataTraceEnabled: !If [IsProduction, false, true]
MetricsEnabled: true
ThrottlingRateLimit: 100
ThrottlingBurstLimit: 200
Variables:
Environment: !Ref Environment
LambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref MyLambdaFunction
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGatewayRestApi}/*/*/*"
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: !Sub "${AWS::StackName}-authorizer"
Type: COGNITO_USER_POOLS
RestApiId: !Ref ApiGatewayRestApi
ProviderARNs:
- !Ref CognitoUserPoolArn
IdentitySource: method.request.header.Authorization
AuthorizerResultTtlInSeconds: 300
Outputs:
ApiEndpoint:
Description: API Gateway endpoint URL
Value: !Sub "https://${ApiGatewayRestApi}.execute-api.${AWS::Region}.amazonaws.com/${DeployStage}/items"API Gateway HTTP API with Lambda
Resources:
HttpApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub "${AWS::StackName}-http-api"
ProtocolType: HTTP
CorsConfiguration:
AllowOrigins:
- !If [IsProduction, !Ref ProductionDomain, "*"]
AllowMethods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
AllowHeaders:
- "*"
MaxAge: 86400
HttpApiStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
ApiId: !Ref HttpApi
StageName: !Ref DeployStage
AutoDeploy: true
DefaultRouteSettings:
DetailedMetricsEnabled: true
ThrottlingBurstLimit: 100
ThrottlingRateLimit: 50
HttpApiIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref HttpApi
IntegrationType: AWS_PROXY
IntegrationUri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations"
PayloadFormatVersion: "2.0"
HttpApiRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref HttpApi
RouteKey: ANY /items/{id}
Target: !Sub "integrations/${HttpApiIntegration.Id}"Event Sources
SQS Event Source
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-sqs-processor"
Runtime: python3.11
Handler: sqs_handler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/sqs-processor.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
Queue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-queue"
VisibilityTimeout: 360
MessageRetentionPeriod: 1209600
RedrivePolicy:
deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn
maxReceiveCount: 5
DeadLetterQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-dlq"
EventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
EventSourceArn: !GetAtt Queue.Arn
BatchSize: 10
MaximumBatchingWindowInSeconds: 60
ScalingConfig:
MaximumConcurrency: 10
FilterCriteria:
Filters:
- Pattern: '{"body": {"messageType": ["order", "notification"]}}'
Enabled: true
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-sqs-role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole
Policies:
- PolicyName: !Sub "${AWS::StackName}-dlq-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- sqs:DeleteMessage
- sqs:ReceiveMessage
Resource: !GetAtt DeadLetterQueue.ArnSNS Event Source
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-sns-processor"
Runtime: python3.11
Handler: sns_handler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/sns-processor.zip
Topic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Sub "${AWS::StackName}-topic"
DisplayName: !Sub "${AWS::StackName} Notifications"
Subscription:
- Endpoint: !GetAtt MyLambdaFunction.Arn
Protocol: lambda
Tags:
- Key: Environment
Value: !Ref Environment
TopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
Topics:
- !Ref Topic
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: sns.amazonaws.com
Action: sns:Publish
Resource: !Ref Topic
LambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref MyLambdaFunction
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref TopicEventBridge (CloudWatch Events)
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-scheduler"
Runtime: python3.11
Handler: scheduler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/scheduler.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
ScheduledRule:
Type: AWS::Events::Rule
Properties:
Name: !Sub "${AWS::StackName}-scheduled-rule"
ScheduleExpression: "rate(5 minutes)"
State: ENABLED
Targets:
- Id: !Ref MyLambdaFunction
Arn: !GetAtt MyLambdaFunction.Arn
RetryPolicy:
MaximumEventAgeInSeconds: 86400
MaximumRetryAttempts: 3
LambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref MyLambdaFunction
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt ScheduledRule.ArnS3 Event Source
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-s3-processor"
Runtime: python3.11
Handler: s3_handler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/s3-processor.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-uploads-${AWS::AccountId}-${AWS::Region}"
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
VersioningConfiguration:
Status: Enabled
NotificationConfiguration:
LambdaConfigurations:
- Event: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: suffix
Value: .csv
Function: !GetAtt MyLambdaFunction.Arn
- Event: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: processed/
Function: !GetAtt MyLambdaFunction.Arn
LambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref MyLambdaFunction
Action: lambda:InvokeFunction
Principal: s3.amazonaws.com
SourceArn: !GetAtt Bucket.ArnStep Functions Integration
AWSTemplateFormatVersion: 2010-09-09
Description: Step Functions with Lambda tasks
Resources:
# Lambda functions for Step Functions
ProcessItemFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-process-item"
Runtime: python3.11
Handler: process_item.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/process-item.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
ValidateItemFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-validate-item"
Runtime: python3.11
Handler: validate_item.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/validate-item.zip
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
NotifyCompletionFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-notify-completion"
Runtime: python3.11
Handler: notify.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/notify.zip
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
# Step Functions State Machine
ProcessingStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
StateMachineName: !Sub "${AWS::StackName}-processor"
StateMachineType: STANDARD
DefinitionString: !Sub |
{
"Comment": "Item processing state machine",
"StartAt": "ValidateItem",
"States": {
"ValidateItem": {
"Type": "Task",
"Resource": "${ValidateItemFunction.Arn}",
"Retry": [
{
"ErrorEquals": ["States.TaskFailed"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2
}
],
"Next": "ProcessItem"
},
"ProcessItem": {
"Type": "Task",
"Resource": "${ProcessItemFunction.Arn}",
"Retry": [
{
"ErrorEquals": ["States.TaskFailed"],
"IntervalSeconds": 5,
"MaxAttempts": 2,
"BackoffRate": 2
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Next": "HandleFailure"
}
],
"Next": "NotifyCompletion"
},
"NotifyCompletion": {
"Type": "Task",
"Resource": "${NotifyCompletionFunction.Arn}",
"End": true
},
"HandleFailure": {
"Type": "Pass",
"End": true
}
}
}
RoleArn: !GetAtt StepFunctionsExecutionRole.Arn
LoggingConfiguration:
Level: ALL
IncludeExecutionData: true
Destinations:
- CloudWatchLogsLogGroup: !Ref StateMachineLogGroup
StepFunctionsExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-sfn-role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: states.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: !Sub "${AWS::StackName}-lambda-invoke"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource:
- !GetAtt ProcessItemFunction.Arn
- !GetAtt ValidateItemFunction.Arn
- !GetAtt NotifyCompletionFunction.Arn
StateMachineLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/state-machine/${AWS::StackName}"
RetentionInDays: 30Cold Start Optimization
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function optimized for cold start
Parameters:
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
Resources:
# Use AWS::Serverless::Function for better cold start
OptimizedLambdaFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-optimized"
CodeUri: s3://bucket/function.zip
Handler: app.handler
Runtime: python3.11
MemorySize: 512
Timeout: 30
EphemeralStorage:
Size: 1024
SnapStart:
ApplyOn: PublishedVersions
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: !If [IsProduction, 5, 0]
Layers:
- !Ref CommonDependenciesLayer
Environment:
Variables:
PYTHONPATH: "/var/task:/opt"
Policies:
- AWSLambdaVPCAccessExecutionRole
- AmazonS3ReadOnlyAccess
VpcConfig:
SecurityGroupIds:
- !Ref LambdaSecurityGroup
SubnetIds: !Ref PrivateSubnetIds
EventInvokeConfig:
MaximumEventAgeInSeconds: 3600
MaximumRetryAttempts: 2
# Optimized layer with pre-installed dependencies
CommonDependenciesLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-dependencies"
Description: Pre-installed Python dependencies for Lambda
ContentUri: s3://bucket/layers/dependencies.zip
CompatibleRuntimes:
- python3.11
CompatibleArchitectures:
- x86_64
RetentionPolicy: Retain
Conditions:
IsProduction: !Equals [!Ref Environment, production]
Outputs:
FunctionArn:
Description: Lambda function ARN
Value: !GetAtt OptimizedLambdaFunction.Arn
FunctionUrl:
Description: Lambda function URL for direct invocation
Value: !GetAtt OptimizedLambdaFunction.UrlMonitoring and Logging
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda with comprehensive monitoring
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-monitored"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
Role: !GetAtt LambdaExecutionRole.Arn
TracingConfig:
Mode: Active
# Log group with retention
LambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${AWS::StackName}-monitored"
RetentionInDays: 30
KmsKeyId: !Ref LogKmsKey
# Metric filter for errors
ErrorMetricFilter:
Type: AWS::Logs::MetricFilter
Properties:
LogGroupName: !Ref LambdaLogGroup
FilterPattern: 'ERROR'
MetricTransformations:
- MetricValue: "1"
MetricNamespace: !Sub "${AWS::StackName}/Lambda"
MetricName: ErrorCount
# CloudWatch Alarms
HighErrorRateAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-error-rate"
AlarmDescription: Alert when error rate exceeds threshold
MetricName: Errors
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref MyLambdaFunction
Statistic: Sum
Period: 60
EvaluationPeriods: 5
Threshold: 10
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref AlertTopic
HighThrottlesAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-throttles"
AlarmDescription: Alert when throttling occurs
MetricName: Throttles
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref MyLambdaFunction
Statistic: Sum
Period: 60
EvaluationPeriods: 3
Threshold: 5
ComparisonOperator: GreaterThanThreshold
AlertTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Sub "${AWS::StackName}-alerts"
# Lambda Destination for async invocations
LambdaDestination:
Type: AWS::Lambda::EventInvokeConfig
Properties:
FunctionName: !Ref MyLambdaFunction
MaximumEventAgeInSeconds: 3600
MaximumRetryAttempts: 2
Qualifier: $LATESTConditions and Transform
Conditions for Environment-Specific Resources
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda with conditional resources
Parameters:
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
Description: Deployment environment
Conditions:
IsProduction: !Equals [!Ref Environment, production]
IsStaging: !Equals [!Ref Environment, staging]
CreateDeadLetterQueue: !Or [!Equals [!Ref Environment, staging], !Equals [!Ref Environment, production]]
EnableXray: !Not [!Equals [!Ref Environment, dev]]
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-function"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: !Sub "lambda/${Environment}/function.zip"
Timeout: !If [IsProduction, 60, 30]
MemorySize: !If [IsProduction, 512, 256]
Role: !GetAtt LambdaExecutionRole.Arn
TracingConfig: !If
- EnableXray
- Mode: Active
- !Ref AWS::NoValue
Environment:
Variables:
LOG_LEVEL: !If [IsProduction, INFO, DEBUG]
DeadLetterQueue:
Type: AWS::SQS::Queue
Condition: CreateDeadLetterQueue
Properties:
QueueName: !Sub "${AWS::StackName}-dlq"Transform for Code Reuse
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Using SAM Transform for Lambda
Globals:
Function:
Timeout: 30
Runtime: python3.11
Tracing: Active
Environment:
Variables:
LOG_LEVEL: INFO
Metadata:
DockerBuild: true
Dockerfile: Dockerfile
DockerContext: lambda_function/
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-sam-function"
Handler: app.handler
CodeUri: lambda_function/
Policies:
- S3ReadPolicy:
BucketName: !Ref DataBucket
- DynamoDBReadPolicy:
TableName: !Ref DataTable
Events:
Api:
Type: Api
Properties:
Path: /items
Method: get
SqsQueue:
Type: SQS
Properties:
Queue: !GetAtt Queue.Arn
BatchSize: 10
AutoPublishAlias: !Ref Environment
DeploymentPreference:
Type: !Ref DeploymentConfig
Alarms:
- !Ref ErrorAlarm
- !Ref LatencyAlarm
DataTable:
Type: AWS::Serverless::SimpleTable
Properties:
TableName: !Sub "${AWS::StackName}-table"
PrimaryKey:
Name: id
Type: String
Parameters:
Environment:
Type: String
Default: dev
DeploymentConfig:
Type: String
Default: AllAtOnce
AllowedValues:
- Canary10Percent5Minutes
- Canary10Percent10Minutes
- Canary10Percent15Minutes
- AllAtOnce
- Linear10PercentEvery1Minute
- Linear10PercentEvery2Minutes
- Linear10PercentEvery3MinutesBest Practices
Security
- Use IAM roles with minimum necessary permissions
- Encrypt environment variables with KMS
- Use VPC for private resource access
- Configure resource-based policies for invocations
- Enable AWS WAF for API Gateway protection
- Use API keys and throttling for protection
Performance
- Choose memory size based on profiling
- Use provisioned concurrency for critical latency
- Optimize package size for cold start
- Use layers for shared dependencies
- Pre-compile code for interpreted languages
- Consider SnapStart for Java/.NET
Monitoring
- Enable detailed metrics and tracing
- Configure appropriate log retention
- Create alarms for errors and throttling
- Use Lambda destinations for async error handling
- Implement distributed tracing
Deployment
- Use change sets before deployment
- Test templates with cfn-lint
- Organize stacks by lifecycle and ownership
- Use nested stacks for modularity
- Implement blue/green deployments
CloudFormation Stack Management Best Practices
Stack Policies
Stack policies protect stack resources from unintentional updates that could cause critical changes or deletions.
Resources:
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
# Function configuration
# Stack policy to protect Lambda function from updates
StackPolicy:
Type: AWS::CloudFormation::StackPolicy
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal: "*"
Action: "Update:*"
Resource: "*"
- Effect: Deny
Principal: "*"
Action:
- Update:Replace
- Update:Delete
Resource:
- LogicalId: LambdaFunction
ResourceType: AWS::Lambda::Function
Condition:
StringEquals:
ResourceAttribute: Arn:
Fn::Ref: LambdaFunctionTermination Protection
Enable termination protection to prevent accidental stack deletion, especially for production environments.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with termination protection
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-function"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
Role: !GetAtt LambdaExecutionRole.Arn
# Enable termination protection (must be set during stack creation)
# This is a stack-level attribute, not a resourceImportant: Termination protection must be enabled during stack creation via AWS Console, CLI, or API:
aws cloudformation create-stack \
--stack-name my-lambda-stack \
--template-body file://template.yaml \
--enable-termination-protection \
--capabilities CAPABILITY_IAMDrift Detection
Detect when infrastructure has diverged from the CloudFormation template.
Resources:
# All Lambda resources support drift detection
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-function"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
LOG_LEVEL: !Ref LogLevelCLI commands for drift detection:
# Detect drift on a stack
aws cloudformation detect-drift --stack-name my-lambda-stack
# Get drift detection status
aws cloudformation describe-stack-drift-detection-status \
--stack-drift-detection-id <detection-id>
# Get resource drift status
aws cloudformation describe-stack-resource-drifts \
--stack-name my-lambda-stack
# Compare actual vs expected resource properties
aws cloudformation get-stack-policy --stack-name my-lambda-stackChange Sets
Use change sets to preview and review stack changes before execution.
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-function"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
Role: !GetAtt LambdaExecutionRole.Arn
MemorySize: !Ref MemorySize
Timeout: !Ref Timeout
Parameters:
MemorySize:
Type: Number
Default: 256
Description: Memory allocation in MB
Timeout:
Type: Number
Default: 30
Description: Function timeout in secondsChange set workflow:
# 1. Create a change set
aws cloudformation create-change-set \
--stack-name my-lambda-stack \
--change-set-name my-changeset \
--template-body file://template.yaml \
--capabilities CAPABILITY_IAM \
--parameters ParameterKey=MemorySize,ParameterValue=512
# 2. Describe the change set to review changes
aws cloudformation describe-change-set \
--stack-name my-lambda-stack \
--change-set-name my-changeset
# 3. Execute the change set
aws cloudformation execute-change-set \
--stack-name my-lambda-stack \
--change-set-name my-changeset
# Or delete if changes are not acceptable
aws cloudformation delete-change-set \
--stack-name my-lambda-stack \
--change-set-name my-changesetChange set types:
CREATE: For new stacksUPDATE: For existing stacksIMPORT: For importing existing resources
Related Resources
Additional Files
For complete details on resources and their properties, see:
- REFERENCE.md - Detailed reference guide for all CloudFormation resources
- EXAMPLES.md - Complete production-ready examples
AWS CloudFormation Lambda - Examples
This file contains comprehensive examples for Lambda serverless patterns with CloudFormation.
Example 1: Lambda with API Gateway REST and Cognito Authorization
Complete API with Lambda backend and Cognito user pool authorization.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda API with API Gateway REST and Cognito authorization
Parameters:
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
FunctionName:
Type: String
Default: api-function
Runtime:
Type: String
Default: python3.11
Handler:
Type: String
Default: app.handler
CodeBucket:
Type: String
Description: S3 bucket containing Lambda code
CognitoUserPoolId:
Type: AWS::Cognito::UserPool::Id
Description: Cognito User Pool ID
DomainName:
Type: String
Default: api.example.com
Mappings:
EnvironmentConfig:
dev:
MemorySize: 256
Timeout: 30
ThrottlingRateLimit: 100
ThrottlingBurstLimit: 200
staging:
MemorySize: 512
Timeout: 60
ThrottlingRateLimit: 500
ThrottlingBurstLimit: 1000
production:
MemorySize: 1024
Timeout: 120
ThrottlingRateLimit: 1000
ThrottlingBurstLimit: 2000
Conditions:
IsProduction: !Equals [!Ref Environment, production]
Resources:
# IAM Role for Lambda
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-lambda-role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
Policies:
- PolicyName: !Sub "${AWS::StackName}-dynamodb-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: !GetAtt DataTable.Arn
- PolicyName: !Sub "${AWS::StackName}-secrets-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource: !Ref SecretsArn
# Lambda Function
ApiFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${FunctionName}-${Environment}"
Runtime: !Ref Runtime
Handler: !Ref Handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: !Sub "lambda/${Environment}/api.zip"
MemorySize: !FindInMap [EnvironmentConfig, !Ref Environment, MemorySize]
Timeout: !FindInMap [EnvironmentConfig, !Ref Environment, Timeout]
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
LOG_LEVEL: !If [IsProduction, INFO, DEBUG]
TABLE_NAME: !Ref DataTable
TracingConfig:
Mode: !If [IsProduction, Active, PassThrough]
Tags:
- Key: Environment
Value: !Ref Environment
- Key: ManagedBy
Value: CloudFormation
# DynamoDB Table
DataTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "${AWS::StackName}-${Environment}"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
- AttributeName: gsi1pk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
GlobalSecondaryIndexes:
- IndexName: gsi1
KeySchema:
- AttributeName: gsi1pk
KeyType: HASH
- AttributeName: pk
KeyType: RANGE
Projection:
ProjectionType: ALL
# API Gateway REST API
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: !Sub "${AWS::StackName}-api-${Environment}"
Description: REST API for Lambda backend
EndpointConfiguration:
Types:
- REGIONAL
MinimumCompressionSize: 1024
# API Gateway Resources
ApiGatewayResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref ApiGatewayRestApi
ParentId: !GetAtt ApiGatewayRestApi.RootResourceId
PathPart: items
ApiGatewayItemIdResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref ApiGatewayRestApi
ParentId: !Ref ApiGatewayResource
PathPart: "{id}"
# API Gateway Methods
ApiGatewayMethodGet:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref ApiGatewayRestApi
ResourceId: !Ref ApiGatewayResource
HttpMethod: GET
AuthorizationType: COGNITO_USER_POOLS
AuthorizerId: !Ref ApiGatewayAuthorizer
RequestParameters:
method.request.querystring.limit: false
method.request.querystring.startkey: false
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${ApiFunction.Arn}/invocations"
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
method.response.header.Content-Type: "'application/json'"
- StatusCode: 400
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
PassthroughBehavior: WHEN_NO_MATCH
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: Empty
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
method.response.header.Content-Type: true
ApiGatewayMethodPost:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref ApiGatewayRestApi
ResourceId: !Ref ApiGatewayResource
HttpMethod: POST
AuthorizationType: COGNITO_USER_POOLS
AuthorizerId: !Ref ApiGatewayAuthorizer
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${ApiFunction.Arn}/invocations"
IntegrationResponses:
- StatusCode: 201
- StatusCode: 400
MethodResponses:
- StatusCode: 201
ResponseModels:
application/json: Empty
- StatusCode: 400
ResponseModels:
application/json: Empty
ApiGatewayMethodGetById:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref ApiGatewayRestApi
ResourceId: !Ref ApiGatewayItemIdResource
HttpMethod: GET
AuthorizationType: COGNITO_USER_POOLS
AuthorizerId: !Ref ApiGatewayAuthorizer
RequestParameters:
method.request.path.id: true
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${ApiFunction.Arn}/invocations"
# API Gateway Authorizer
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: !Sub "${AWS::StackName}-authorizer"
Type: COGNITO_USER_POOLS
RestApiId: !Ref ApiGatewayRestApi
ProviderARNs:
- !Sub "arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/${CognitoUserPoolId}"
IdentitySource: method.request.header.Authorization
AuthorizerResultTtlInSeconds: 300
# API Gateway Deployment
ApiGatewayDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn:
- ApiGatewayMethodGet
- ApiGatewayMethodPost
- ApiGatewayMethodGetById
Properties:
RestApiId: !Ref ApiGatewayRestApi
StageName: !Ref Environment
StageDescription:
LoggingLevel: !If [IsProduction, INFO, ERROR]
DataTraceEnabled: !If [IsProduction, false, true]
MetricsEnabled: true
ThrottlingRateLimit: !FindInMap [EnvironmentConfig, !Ref Environment, ThrottlingRateLimit]
ThrottlingBurstLimit: !FindInMap [EnvironmentConfig, !Ref Environment, ThrottlingBurstLimit]
# Lambda Permissions
LambdaPermissionForApiGateway:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref ApiFunction
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGatewayRestApi}/*/*/*"
Outputs:
ApiEndpoint:
Description: API Gateway endpoint URL
Value: !Sub "https://${ApiGatewayRestApi}.execute-api.${AWS::Region}.amazonaws.com/${Environment}"
ApiFunctionArn:
Description: Lambda function ARN
Value: !GetAtt ApiFunction.Arn
TableName:
Description: DynamoDB table name
Value: !Ref DataTableExample 2: Lambda with SQS Event Source and DLQ
Lambda function processing messages from SQS queue with dead letter queue.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with SQS event source and DLQ
Parameters:
Environment:
Type: String
Default: dev
Resources:
# Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: SqsProcessingPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- sqs:DeleteMessage
- sqs:ReceiveMessage
- sqs:GetQueueAttributes
Resource: !GetAtt ProcessingQueue.Arn
- Effect: Allow
Action:
- sqs:DeleteMessage
- sqs:SendMessage
Resource: !GetAtt DeadLetterQueue.Arn
# Lambda Function
SqsProcessorFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-sqs-processor"
Runtime: python3.11
Handler: sqs_handler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/sqs-processor.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
DLQ_URL: !Ref DeadLetterQueue
# Main Queue
ProcessingQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-processing-${Environment}"
VisibilityTimeout: 360
MessageRetentionPeriod: 1209600
RedrivePolicy:
deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn
maxReceiveCount: 5
KmsMasterKeyId: !Ref QueueKmsKey
Tags:
- Key: Environment
Value: !Ref Environment
# Dead Letter Queue
DeadLetterQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-dlq-${Environment}"
MessageRetentionPeriod: 604800
KmsMasterKeyId: !Ref QueueKmsKey
# Event Source Mapping
EventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref SqsProcessorFunction
EventSourceArn: !GetAtt ProcessingQueue.Arn
BatchSize: 10
MaximumBatchingWindowInSeconds: 60
ScalingConfig:
MaximumConcurrency: 10
FilterCriteria:
Filters:
- Pattern: '{"body": {"messageType": ["order", "notification"]}}'
Enabled: true
Outputs:
QueueUrl:
Description: SQS Queue URL
Value: !Ref ProcessingQueue
QueueArn:
Description: SQS Queue ARN
Value: !GetAtt ProcessingQueue.Arn
DlqUrl:
Description: Dead Letter Queue URL
Value: !Ref DeadLetterQueueExample 3: Lambda with SNS Topic Subscription
Lambda function subscribed to SNS topic for event processing.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with SNS topic subscription
Parameters:
Environment:
Type: String
Default: prod
Resources:
# Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# Lambda Function
SnsProcessorFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-sns-processor"
Runtime: python3.11
Handler: sns_handler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/sns-processor.zip
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
# SNS Topic
NotificationTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Sub "${AWS::StackName}-notifications-${Environment}"
DisplayName: !Sub "${AWS::StackName} Notifications"
Subscription:
- Endpoint: !GetAtt SnsProcessorFunction.Arn
Protocol: lambda
Tags:
- Key: Environment
Value: !Ref Environment
# Topic Policy to allow SNS to invoke Lambda
TopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
Topics:
- !Ref NotificationTopic
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: sns.amazonaws.com
Action: sns:Publish
Resource: !Ref NotificationTopic
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sns:Subscribe
Resource: !Ref NotificationTopic
# Lambda Permission for SNS
LambdaPermissionForSns:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref SnsProcessorFunction
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref NotificationTopic
Outputs:
TopicArn:
Description: SNS Topic ARN
Value: !Ref NotificationTopic
TopicName:
Description: SNS Topic Name
Value: !GetAtt NotificationTopic.TopicNameExample 4: Lambda with EventBridge (CloudWatch Events)
Scheduled Lambda function with EventBridge rule.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with EventBridge scheduled execution
Parameters:
Environment:
Type: String
Default: production
ScheduleExpression:
Type: String
Default: "rate(5 minutes)"
Resources:
# Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: CloudWatchPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- cloudwatch:PutMetricData
Resource: "*"
# Lambda Function
ScheduledFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-scheduler-${Environment}"
Runtime: python3.11
Handler: scheduler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/scheduler.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
# EventBridge Rule
ScheduledRule:
Type: AWS::Events::Rule
Properties:
Name: !Sub "${AWS::StackName}-scheduled-rule-${Environment}"
Description: Triggers Lambda function on schedule
ScheduleExpression: !Ref ScheduleExpression
State: ENABLED
Targets:
- Id: ScheduledFunction
Arn: !GetAtt ScheduledFunction.Arn
RetryPolicy:
MaximumEventAgeInSeconds: 86400
MaximumRetryAttempts: 3
# Lambda Permission for EventBridge
LambdaPermissionForEventBridge:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref ScheduledFunction
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt ScheduledRule.Arn
Outputs:
RuleArn:
Description: EventBridge Rule ARN
Value: !GetAtt ScheduledRule.ArnExample 5: Lambda with S3 Event Notification
Lambda function triggered by S3 object creation events.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with S3 event triggers
Parameters:
Environment:
Type: String
Default: dev
Resources:
# Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: S3AccessPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
Resource: !Sub "${UploadBucket.Arn}/*"
- Effect: Allow
Action:
- s3:GetBucketNotification
- s3:PutBucketNotification
Resource: !Ref UploadBucket
# Lambda Function
S3ProcessorFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-s3-processor"
Runtime: python3.11
Handler: s3_handler.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/s3-processor.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
OUTPUT_BUCKET: !Ref ProcessedBucket
# Upload Bucket with Lambda notification configuration
UploadBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-uploads-${AWS::AccountId}-${AWS::Region}"
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
VersioningConfiguration:
Status: Enabled
NotificationConfiguration:
LambdaConfigurations:
- Event: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: suffix
Value: .csv
Function: !GetAtt S3ProcessorFunction.Arn
- Event: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: incoming/
Function: !GetAtt S3ProcessorFunction.Arn
- Event: s3:ObjectRemoved:*
Function: !GetAtt S3ProcessorFunction.Arn
CorsConfiguration:
CorsRules:
- AllowedHeaders:
- "*"
AllowedMethods:
- GET
- PUT
- POST
AllowedOrigins:
- "*"
MaxAge: 3600
Tags:
- Key: Environment
Value: !Ref Environment
# Processed Bucket
ProcessedBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-processed-${AWS::AccountId}-${AWS::Region}"
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
# Lambda Permission for S3
LambdaPermissionForS3:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref S3ProcessorFunction
Action: lambda:InvokeFunction
Principal: s3.amazonaws.com
SourceArn: !GetAtt UploadBucket.Arn
Outputs:
UploadBucketName:
Description: Upload bucket name
Value: !Ref UploadBucket
UploadBucketArn:
Description: Upload bucket ARN
Value: !GetAtt UploadBucket.ArnExample 6: Lambda with Step Functions Workflow
Lambda functions orchestrated by Step Functions state machine.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda functions with Step Functions workflow orchestration
Parameters:
Environment:
Type: String
Default: prod
Resources:
# Lambda Functions
ValidateItemFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-validate"
Runtime: python3.11
Handler: validate.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/validate.zip
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
ProcessItemFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-process"
Runtime: python3.11
Handler: process.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/process.zip
Timeout: 300
Role: !GetAtt LambdaExecutionRole.Arn
EnrichItemFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-enrich"
Runtime: python3.11
Handler: enrich.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/enrich.zip
Timeout: 120
Role: !GetAtt LambdaExecutionRole.Arn
NotifyCompletionFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-notify"
Runtime: python3.11
Handler: notify.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/notify.zip
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
# Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# Step Functions Execution Role
StepFunctionsExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-sfn-role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: states.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: LambdaInvokePolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource:
- !GetAtt ValidateItemFunction.Arn
- !GetAtt ProcessItemFunction.Arn
- !GetAtt EnrichItemFunction.Arn
- !GetAtt NotifyCompletionFunction.Arn
- PolicyName: CloudWatchLogsPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub "${StateMachineLogGroup.Arn}:*"
# State Machine Log Group
StateMachineLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/state-machine/${AWS::StackName}"
RetentionInDays: 30
# Step Functions State Machine
ProcessingStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
StateMachineName: !Sub "${AWS::StackName}-processor-${Environment}"
StateMachineType: STANDARD
DefinitionString: !Sub |
{
"Comment": "Item processing state machine",
"StartAt": "ValidateItem",
"States": {
"ValidateItem": {
"Type": "Task",
"Resource": "${ValidateItemFunction.Arn}",
"Retry": [
{
"ErrorEquals": ["States.TaskFailed"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2
}
],
"Next": "ProcessItem"
},
"ProcessItem": {
"Type": "Task",
"Resource": "${ProcessItemFunction.Arn}",
"Retry": [
{
"ErrorEquals": ["States.TaskFailed"],
"IntervalSeconds": 5,
"MaxAttempts": 2,
"BackoffRate": 2
}
],
"Next": "EnrichItem"
},
"EnrichItem": {
"Type": "Task",
"Resource": "${EnrichItemFunction.Arn}",
"Retry": [
{
"ErrorEquals": ["States.TaskFailed"],
"IntervalSeconds": 3,
"MaxAttempts": 3,
"BackoffRate": 1.5
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Next": "HandleEnrichmentFailure"
}
],
"Next": "NotifyCompletion"
},
"NotifyCompletion": {
"Type": "Task",
"Resource": "${NotifyCompletionFunction.Arn}",
"End": true
},
"HandleEnrichmentFailure": {
"Type": "Pass",
"ResultPath": "$.error",
"Next": "NotifyCompletion"
}
}
}
RoleArn: !GetAtt StepFunctionsExecutionRole.Arn
LoggingConfiguration:
Level: ALL
IncludeExecutionData: true
Destinations:
- CloudWatchLogsLogGroup: !Ref StateMachineLogGroup
Tags:
- Key: Environment
Value: !Ref Environment
Outputs:
StateMachineArn:
Description: Step Functions State Machine ARN
Value: !Ref ProcessingStateMachineExample 7: Lambda with Layers
Lambda function using shared layers for dependencies.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with shared layers
Parameters:
Environment:
Type: String
Default: dev
Resources:
# Common Library Layer
CommonLibraryLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-common-lib"
Description: Common utilities, logger, and validators
Content:
S3Bucket: !Ref LayersBucket
S3Key: layers/common-lib.zip
CompatibleRuntimes:
- python3.9
- python3.10
- python3.11
- python3.12
CompatibleArchitectures:
- x86_64
- arm64
# Data Processing Layer
DataProcessingLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-data-processing"
Description: Data processing utilities (pandas, numpy)
Content:
S3Bucket: !Ref LayersBucket
S3Key: layers/data-processing.zip
CompatibleRuntimes:
- python3.11
- python3.12
CompatibleArchitectures:
- x86_64
# ML Utilities Layer
MlUtilitiesLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-ml-utilities"
Description: ML utilities (scikit-learn, torch)
Content:
S3Bucket: !Ref LayersBucket
S3Key: layers/ml-utilities.zip
CompatibleRuntimes:
- python3.11
- python3.12
CompatibleArchitectures:
- x86_64
# Lambda Function using layers
DataProcessorFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-data-processor"
Runtime: python3.11
Handler: processor.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/data-processor.zip
MemorySize: 2048
Timeout: 900
Role: !GetAtt LambdaExecutionRole.Arn
Layers:
- !Ref CommonLibraryLayer
- !Ref DataProcessingLayer
Environment:
Variables:
PYTHONPATH: "/var/task:/opt"
ENVIRONMENT: !Ref Environment
# Lambda Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Outputs:
CommonLibraryLayerArn:
Description: Common library layer ARN
Value: !Ref CommonLibraryLayer
DataProcessingLayerArn:
Description: Data processing layer ARN
Value: !Ref DataProcessingLayerExample 8: Lambda with Provisioned Concurrency
Lambda function with provisioned concurrency for predictable latency.
AWSTemplateFormatVersion: 2010-09-09
Description: Lambda function with provisioned concurrency for low latency
Parameters:
Environment:
Type: String
Default: prod
ProvisionedConcurrentExecutions:
Type: Number
Default: 10
Description: Number of provisioned concurrent executions
Resources:
# Lambda Function
LowLatencyFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-low-latency"
Runtime: python3.11
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/low-latency.zip
MemorySize: 1024
Timeout: 30
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
# Lambda Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# Provisioned Concurrency Configuration
ProvisionedConcurrencyConfig:
Type: AWS::Lambda::ProvisionedConcurrencyConfig
Properties:
FunctionName: !Ref LowLatencyFunction
ProvisionedConcurrentExecutions: !Ref ProvisionedConcurrentExecutions
Qualifier: $LATEST
ProvisionedExecutionTarget:
AllocationStrategy: PRICE_OPTIMIZED
# Auto Alias
LambdaVersion:
Type: AWS::Lambda::Version
Properties:
FunctionName: !Ref LowLatencyFunction
Description: Version with provisioned concurrency
Outputs:
ProvisionedConcurrencyArn:
Description: Provisioned concurrency configuration ARN
Value: !Ref ProvisionedConcurrencyConfig
FunctionVersion:
Description: Lambda function version
Value: !Ref LambdaVersionExample 9: Complete Production Lambda with Monitoring
Complete production-ready Lambda with CloudWatch monitoring, alarms, and logging.
AWSTemplateFormatVersion: 2010-09-09
Description: Production Lambda with comprehensive monitoring
Parameters:
Environment:
Type: String
Default: production
FunctionName:
Type: String
Default: api-function
Runtime:
Type: String
Default: python3.11
AlertEmail:
Type: String
Description: Email for alert notifications
Mappings:
EnvironmentConfig:
dev:
MemorySize: 256
Timeout: 30
ReservedConcurrency: 10
staging:
MemorySize: 512
Timeout: 60
ReservedConcurrency: 50
production:
MemorySize: 1024
Timeout: 120
ReservedConcurrency: 100
Resources:
# IAM Role with CloudWatch full access
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-role-${Environment}"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
Policies:
- PolicyName: CloudWatchMetricsPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- cloudwatch:PutMetricData
Resource: "*"
# Lambda Function
ProductionFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${FunctionName}-${Environment}"
Runtime: !Ref Runtime
Handler: app.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: !Sub "lambda/${Environment}/function.zip"
MemorySize: !FindInMap [EnvironmentConfig, !Ref Environment, MemorySize]
Timeout: !FindInMap [EnvironmentConfig, !Ref Environment, Timeout]
Role: !GetAtt LambdaExecutionRole.Arn
ReservedConcurrentExecutions: !FindInMap [EnvironmentConfig, !Ref Environment, ReservedConcurrency]
Environment:
Variables:
ENVIRONMENT: !Ref Environment
LOG_LEVEL: INFO
TracingConfig:
Mode: Active
# Log Group with encryption
LambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${ProductionFunction}"
RetentionInDays: 30
KmsKeyId: !Ref LogKmsKey
# Metric Filter for Errors
ErrorMetricFilter:
Type: AWS::Logs::MetricFilter
Properties:
LogGroupName: !Ref LambdaLogGroup
FilterPattern: 'ERROR'
MetricTransformations:
- MetricValue: "1"
MetricNamespace: !Sub "${AWS::StackName}/Lambda"
MetricName: ErrorCount
# Metric Filter for Warnings
WarningMetricFilter:
Type: AWS::Logs::MetricFilter
Properties:
LogGroupName: !Ref LambdaLogGroup
FilterPattern: 'WARNING'
MetricTransformations:
- MetricValue: "1"
MetricNamespace: !Sub "${AWS::StackName}/Lambda"
MetricName: WarningCount
# CloudWatch Alarms
HighErrorRateAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-error-rate"
AlarmDescription: Alert when error rate exceeds 1%
MetricName: Errors
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref ProductionFunction
Statistic: Sum
Period: 60
EvaluationPeriods: 5
Threshold: 10
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref AlertTopic
OKActions:
- !Ref AlertTopic
HighLatencyAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-latency"
AlarmDescription: Alert when p99 latency exceeds 5 seconds
MetricName: Duration
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref ProductionFunction
Statistic: p99
Period: 60
EvaluationPeriods: 3
Threshold: 5000
ComparisonOperator: GreaterThanThreshold
HighThrottlesAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-throttles"
AlarmDescription: Alert when throttling occurs
MetricName: Throttles
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref ProductionFunction
Statistic: Sum
Period: 60
EvaluationPeriods: 3
Threshold: 5
ComparisonOperator: GreaterThanThreshold
HighInvocationAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-invocations"
AlarmDescription: Alert on unusual high invocation count
MetricName: Invocations
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref ProductionFunction
Statistic: Sum
Period: 60
EvaluationPeriods: 1
Threshold: 10000
ComparisonOperator: GreaterThanThreshold
# SNS Topic for Alerts
AlertTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Sub "${AWS::StackName}-alerts-${Environment}"
Subscription:
- Endpoint: !Ref AlertEmail
Protocol: email
# Lambda Event Invoke Config
EventInvokeConfig:
Type: AWS::Lambda::EventInvokeConfig
Properties:
FunctionName: !Ref ProductionFunction
MaximumEventAgeInSeconds: 3600
MaximumRetryAttempts: 2
Qualifier: $LATEST
# Lambda URL for direct invocation
LambdaFunctionUrl:
Type: AWS::Lambda::Url
Properties:
AuthType: AWS_IAM
TargetFunctionArn: !GetAtt ProductionFunction.Arn
Cors:
AllowCredentials: true
AllowHeaders:
- "*"
AllowMethods:
- GET
- POST
AllowOrigins:
- "*"
MaxAge: 86400
# Lambda Permission for URL
LambdaPermissionForUrl:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref ProductionFunction
Action: lambda:InvokeFunctionUrl
Principal: "*"
Outputs:
FunctionArn:
Description: Lambda function ARN
Value: !GetAtt ProductionFunction.Arn
FunctionUrl:
Description: Lambda function URL
Value: !GetAtt LambdaFunctionUrl.Url
LogGroupName:
Description: CloudWatch log group name
Value: !Ref LambdaLogGroupExample 10: Lambda with SAM Globals
Using SAM Globals to reduce template repetition.
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Lambda functions with SAM Globals for configuration reuse
Globals:
Function:
Timeout: 30
Runtime: python3.11
Tracing: Active
Environment:
Variables:
LOG_LEVEL: INFO
ENVIRONMENT: !Ref Environment
Metadata:
DockerBuild: true
Dockerfile: Dockerfile
DockerContext: lambda_functions/
VpcConfig:
SecurityGroupIds: !Ref SecurityGroupIds
SubnetIds: !Ref SubnetIds
Parameters:
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
SecurityGroupIds:
Type: List<AWS::EC2::SecurityGroup::Id>
SubnetIds:
Type: List<AWS::EC2::Subnet::Id>
Resources:
# API Function
ApiFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-api"
Handler: api.handler
CodeUri: lambda_functions/api/
MemorySize: 512
Timeout: 60
Policies:
- DynamoDBWritePolicy:
TableName: !Ref DataTable
Events:
ApiEvent:
Type: Api
Properties:
Path: /api/{proxy+}
Method: ANY
RestApiId: !Ref ApiGateway
# Data Processing Function
DataFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-data"
Handler: data.handler
CodeUri: lambda_functions/data/
MemorySize: 2048
Timeout: 300
Policies:
- S3ReadPolicy:
BucketName: !Ref InputBucket
- S3WritePolicy:
BucketName: !Ref OutputBucket
Events:
S3Upload:
Type: S3
Properties:
Bucket: !Ref InputBucket
Events: s3:ObjectCreated:*
# Background Job Function
JobFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-jobs"
Handler: jobs.handler
CodeUri: lambda_functions/jobs/
MemorySize: 256
Policies:
- SQSReadPolicy:
QueueName: !Ref JobQueue
Events:
SqsQueue:
Type: SQS
Properties:
Queue: !GetAtt JobQueue.Arn
BatchSize: 10
# DynamoDB Table
DataTable:
Type: AWS::Serverless::Table
Properties:
TableName: !Sub "${AWS::StackName}-data"
PrimaryKey:
Name: id
Type: String
BillingMode: PAY_PER_REQUEST
# API Gateway
ApiGateway:
Type: AWS::Serverless::Api
Properties:
Name: !Sub "${AWS::StackName}-api"
StageName: !Ref Environment
Cors:
AllowOrigin: "*"
AllowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
# S3 Buckets
InputBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-input-${AWS::AccountId}-${AWS::Region}"
OutputBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-output-${AWS::AccountId}-${AWS::Region}"
# SQS Queue
JobQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-jobs"
VisibilityTimeout: 360
MessageRetentionPeriod: 1209600
Outputs:
ApiEndpoint:
Value: !Sub "https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${Environment}"AWS CloudFormation Lambda - Reference
This reference guide contains detailed information about AWS CloudFormation resources, intrinsic functions, and configurations for Lambda serverless infrastructure.
AWS::Lambda::Function
Creates a Lambda function.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| Code | Code | Yes | The code for the function |
| Handler | String | Yes | The function that Lambda calls to begin execution |
| Role | String | Yes | The ARN of the IAM role that Lambda assumes |
| Runtime | String | Yes | The runtime environment for the function |
| FunctionName | String | No | The name of the function |
| Description | String | No | A description of the function |
| MemorySize | Integer | No | The amount of memory available to the function (128-10240 MB) |
| Timeout | Integer | No | The function execution timeout in seconds (1-900) |
| VpcConfig | VpcConfig | No | The VPC configuration for the function |
| Environment | Environment | No | Environment variables for the function |
| TracingConfig | TracingConfig | No | AWS X-Ray tracing configuration |
| Tags | List of Tag | No | Tags for the function |
| Layers | List of String | No | The layers for the function |
| ReservedConcurrentExecutions | Integer | No | Reserved concurrent executions for the function |
| EphemeralStorage | EphemeralStorage | No | The size of the function's /tmp directory (512-10240 MB) |
| FileSystemConfigs | List of FileSystemConfig | No | The EFS file system connections |
| ImageConfig | ImageConfig | No | The image configuration for container images |
| PackageType | String | No | The package type (Zip or Image) |
| SigningProfileVersionArn | String | No | The ARN of the signing profile |
| SigningJobArn | String | No | The ARN of the signing job |
Code Structure
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
S3ObjectVersion: version-id
# Or for inline code
ZipFile: |
def handler(event, context):
return {"statusCode": 200, "body": "Hello"}Example
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-processor"
Runtime: python3.11
Handler: index.handler
Code:
S3Bucket: !Ref CodeBucket
S3Key: lambda/function.zip
MemorySize: 256
Timeout: 60
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
ENVIRONMENT: !Ref Environment
LOG_LEVEL: INFO
Tags:
- Key: Environment
Value: !Ref EnvironmentAttributes
| Attribute | Description |
|---|---|
| Arn | The ARN of the function |
| FunctionName | The name of the function |
| Runtime | The runtime of the function |
| Handler | The handler of the function |
| MemorySize | The memory size of the function |
| Timeout | The timeout of the function |
| Role | The role ARN of the function |
AWS::Lambda::LayerVersion
Creates a Lambda layer.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| LayerName | String | No | The name of the layer |
| Description | String | No | A description of the layer |
| Content | Content | Yes | The content of the layer |
| CompatibleRuntimes | List of String | No | Compatible runtimes |
| CompatibleArchitectures | List of String | No | Compatible architectures (x86_64, arm64) |
| LicenseInfo | String | No | The layer's license information |
Example
Resources:
CommonLibraryLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-common-lib"
Description: Common utilities for Lambda functions
Content:
S3Bucket: !Ref LayersBucket
S3Key: layers/common-lib.zip
CompatibleRuntimes:
- python3.9
- python3.10
- python3.11
CompatibleArchitectures:
- x86_64
- arm64Attributes
| Attribute | Description |
|---|---|
| LayerVersionArn | The ARN of the layer version |
| LayerArn | The ARN of the layer |
AWS::Lambda::EventSourceMapping
Creates an event source mapping between an event source and a Lambda function.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| FunctionName | String | Yes | The name of the Lambda function |
| EventSourceArn | String | Cond | The ARN of the event source (SQS, Kafka, MQ) |
| BatchSize | Integer | No | The maximum number of records in each batch (1-10000) |
| MaximumBatchingWindowInSeconds | Integer | No | The maximum time to gather records (0-300) |
| ParallelizationFactor | Integer | No | The number of batches to process concurrently (1-10) |
| StartingPosition | String | Cond | The position to start reading (AT_TIMESTAMP, LATEST, TRIM_HORIZON) |
| StartingPositionTimestamp | Integer | Cond | The timestamp to start reading (Unix seconds) |
| FilterCriteria | FilterCriteria | No | Criteria to filter events |
| MaximumRecordAgeInSeconds | Integer | No | Maximum age of records (60-604800) |
| MaximumRetryAttempts | Integer | No | Maximum retry attempts (0-10000) |
| BisectBatchOnFunctionError | Boolean | No | Split batch on function error |
| DestinationConfig | DestinationConfig | No | Destination for failed records |
| Enabled | Boolean | No | Whether the mapping is enabled |
| SourceAccessConfigurations | List of SourceAccessConfiguration | No | Credentials for Kafka and MQ sources |
| Topics | List of String | No | Kafka topics |
| Queues | List of String | No | SQS queue names |
Example
Resources:
EventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
EventSourceArn: !GetAtt Queue.Arn
BatchSize: 10
MaximumBatchingWindowInSeconds: 60
MaximumRecordAgeInSeconds: 604800
MaximumRetryAttempts: 3
Enabled: trueAWS::Lambda::Permission
Grants an AWS service or another account permission to use a function.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| FunctionName | String | Yes | The name or ARN of the Lambda function |
| Action | String | Yes | The action Lambda should perform (lambda:InvokeFunction) |
| Principal | String | Yes | The principal to grant permission to |
| SourceArn | String | Cond | The ARN of the source triggering the function |
| SourceAccount | String | Cond | The AWS account ID of the source |
| EventSourceToken | String | Cond | The event source token for Alexa Smart Home |
| Qualifier | String | Cond | The version or alias of the function |
Example
Resources:
LambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref MyLambdaFunction
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations"AWS::Lambda::ProvisionedConcurrencyConfig
Configures provisioned concurrency for a Lambda function alias or version.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| FunctionName | String | Yes | The name of the Lambda function |
| ProvisionedConcurrentExecutions | Integer | Yes | The amount of provisioned concurrency |
| Qualifier | String | Yes | The alias or version of the function |
| ProvisionedExecutionTarget | ProvisionedExecutionTarget | No | Target allocation strategy |
Example
Resources:
ProvisionedConcurrencyConfig:
Type: AWS::Lambda::ProvisionedConcurrencyConfig
Properties:
FunctionName: !Ref MyLambdaFunction
ProvisionedConcurrentExecutions: 5
Qualifier: $LATEST
ProvisionedExecutionTarget:
AllocationStrategy: PRICE_OPTIMIZEDAWS::Lambda::EventInvokeConfig
Configures options for asynchronous invocation on a Lambda function.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| FunctionName | String | Yes | The name of the Lambda function |
| MaximumEventAgeInSeconds | Integer | No | Maximum age of events (60-21600) |
| MaximumRetryAttempts | Integer | No | Maximum retry attempts (0-2) |
| Qualifier | String | No | The alias or version of the function |
| DestinationConfig | DestinationConfig | No | Destination for successful/failed invocations |
Example
Resources:
EventInvokeConfig:
Type: AWS::Lambda::EventInvokeConfig
Properties:
FunctionName: !Ref MyLambdaFunction
MaximumEventAgeInSeconds: 3600
MaximumRetryAttempts: 2
DestinationConfig:
OnSuccess:
Destination: !Ref SuccessQueue
OnFailure:
Destination: !Ref DeadLetterQueueAWS::Lambda::Url
Creates a function URL for a Lambda function.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| AuthType | String | Yes | The authentication type (AWS_IAM, NONE) |
| TargetFunctionArn | String | Yes | The ARN of the Lambda function |
| Cors | Cors | No | CORS configuration |
| InvokeMode | String | No | The invocation mode (BUFFERED, RESPONSE_STREAM) |
| Qualifier | String | No | The alias or version of the function |
Example
Resources:
LambdaFunctionUrl:
Type: AWS::Lambda::Url
Properties:
AuthType: AWS_IAM
TargetFunctionArn: !GetAtt MyLambdaFunction.Arn
Cors:
AllowCredentials: true
AllowHeaders:
- "*"
AllowMethods:
- GET
- POST
AllowOrigins:
- "*"
MaxAge: 86400Attributes
| Attribute | Description |
|---|---|
| Url | The function URL |
AWS::Serverless::Function
Creates a Lambda function with SAM simplifications.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| CodeUri | String | Yes | The location of the code |
| Handler | String | Yes | The function handler |
| Runtime | String | Yes | The runtime environment |
| Code | Code | No | Inline code (alternative to CodeUri) |
| InlineCode | String | No | Inline code (alternative to CodeUri) |
| Description | String | No | A description of the function |
| MemorySize | Integer | No | The memory allocation (128-10240) |
| Timeout | Integer | No | The function timeout (1-900) |
| Role | String | No | The IAM role ARN |
| Policies | List or Policy | No | IAM policies to attach |
| Environment | Environment | No | Environment variables |
| VpcConfig | VpcConfig | No | The VPC configuration |
| Events | Map of Event | No | Event sources |
| Tags | Map of String | No | Tags |
| Layers | List of String | No | Layers |
| Tracing | String | No | X-Ray tracing (Active or PassThrough) |
| ReservedConcurrentExecutions | Integer | No | Reserved concurrent executions |
| PermissionsBoundary | String | No | Permissions boundary policy |
| EventInvokeConfig | EventInvokeConfig | No | Async invocation config |
| ProvisionedConcurrencyConfig | ProvisionedConcurrencyConfig | No | Provisioned concurrency |
| AutoPublishAlias | String | No | Auto-publish alias on update |
| AutoPublishCodeSha256 | String | No | Code hash for alias update |
| DeploymentPreference | DeploymentPreference | No | Deployment configuration |
| FunctionName | String | No | The function name |
| FileSystemConfigs | List of FileSystemConfig | No | EFS configurations |
| ImageConfig | ImageConfig | No | Image configuration |
| PackageType | String | No | Package type (Zip or Image) |
| Metadata | Metadata | No | Build metadata |
| SnapStart | SnapStart | No | SnapStart configuration |
Example
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-api"
CodeUri: lambda_function/
Handler: app.handler
Runtime: python3.11
MemorySize: 512
Timeout: 30
Policies:
- S3ReadPolicy:
BucketName: !Ref DataBucket
- DynamoDBReadPolicy:
TableName: !Ref DataTable
Environment:
Variables:
LOG_LEVEL: INFO
Events:
Api:
Type: Api
Properties:
Path: /items
Method: get
SqsQueue:
Type: SQS
Properties:
Queue: !GetAtt Queue.Arn
BatchSize: 10
AutoPublishAlias: !Ref EnvironmentAWS::Serverless::LayerVersion
Creates a Lambda layer with SAM simplifications.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| LayerName | String | No | The name of the layer |
| Description | String | No | A description of the layer |
| ContentUri | String | Yes | The location of the layer content |
| CompatibleRuntimes | List of String | No | Compatible runtimes |
| CompatibleArchitectures | List of String | No | Compatible architectures |
| LicenseInfo | String | No | The layer license |
| RetentionPolicy | String | No | Retention policy (Retain or Delete) |
Example
Resources:
DependenciesLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: !Sub "${AWS::StackName}-dependencies"
Description: Python dependencies
ContentUri: layers/dependencies.zip
CompatibleRuntimes:
- python3.11
RetentionPolicy: RetainAWS::ApiGateway::RestApi
Creates a REST API in API Gateway.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| Name | String | No | The name of the REST API |
| Description | String | No | A description of the API |
| EndpointConfiguration | EndpointConfiguration | No | The endpoint configuration |
| Policy | Json | No | The resource policy |
| MinimumCompressionSize | Integer | No | Minimum compression size (0-10485760) |
| DisableExecuteApiEndpoint | Boolean | No | Disable the execute API endpoint |
| BinaryMediaTypes | List of String | No | Binary media types |
| CorsConfiguration | CorsConfiguration | No | CORS configuration |
Example
Resources:
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: !Sub "${AWS::StackName}-api"
Description: REST API for Lambda backend
EndpointConfiguration:
Types:
- REGIONAL
MinimumCompressionSize: 1024AWS::ApiGatewayV2::Api
Creates an HTTP API in API Gateway V2.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| Name | String | No | The name of the API |
| ProtocolType | String | Yes | The protocol type (HTTP) |
| Description | String | No | A description of the API |
| CorsConfiguration | CorsConfiguration | No | CORS configuration |
| DisableExecuteApiEndpoint | Boolean | No | Disable the execute API endpoint |
| RouteSelectionExpression | String | No | The route selection expression |
| Body | Json | No | OpenAPI definition |
| BodyS3Location | S3Location | No | S3 location of OpenAPI definition |
Example
Resources:
HttpApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub "${AWS::StackName}-http-api"
ProtocolType: HTTP
CorsConfiguration:
AllowOrigins:
- "*"
AllowMethods:
- GET
- POST
- PUT
- DELETEAWS::StepFunctions::StateMachine
Creates a Step Functions state machine.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| StateMachineName | String | No | The name of the state machine |
| StateMachineType | String | No | The type (STANDARD or EXPRESS) |
| DefinitionString | Json | Yes | The state machine definition |
| DefinitionS3Location | S3Location | No | S3 location of definition |
| RoleArn | String | Yes | The IAM role ARN |
| LoggingConfiguration | LoggingConfiguration | No | CloudWatch Logs configuration |
| TracingConfiguration | TracingConfiguration | No | X-Ray tracing |
| Tags | List of Tag | No | Tags |
State Types Reference
| Type | Description |
|---|---|
| Task | Execute work using Lambda or other service |
| Choice | Branch based on data |
| Wait | Pause execution |
| Pass | Pass data to next state |
| Parallel | Execute branches in parallel |
| Map | Iterate over items |
| Succeed | End execution successfully |
| Fail | End execution in failure |
Example
Resources:
ProcessingStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
StateMachineName: !Sub "${AWS::StackName}-processor"
StateMachineType: STANDARD
DefinitionString: !Sub |
{
"Comment": "Item processing workflow",
"StartAt": "ValidateItem",
"States": {
"ValidateItem": {
"Type": "Task",
"Resource": "${ValidateItemFunction.Arn}",
"Next": "ProcessItem"
},
"ProcessItem": {
"Type": "Task",
"Resource": "${ProcessItemFunction.Arn}",
"End": true
}
}
}
RoleArn: !GetAtt StepFunctionsExecutionRole.Arn
LoggingConfiguration:
Level: ALL
IncludeExecutionData: trueAWS::SQS::Queue
Creates an SQS queue.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| QueueName | String | No | The name of the queue |
| DelaySeconds | Integer | No | Delivery delay in seconds (0-900) |
| MaximumMessageSize | Integer | No | Max message size (1024-262144) |
| MessageRetentionPeriod | Integer | No | Retention period (60-1209600) |
| ReceiveMessageWaitTimeSeconds | Integer | No | Polling wait time (0-20) |
| VisibilityTimeout | Integer | No | Visibility timeout (0-43200) |
| RedrivePolicy | RedrivePolicy | No | Dead letter queue configuration |
| FifoQueue | Boolean | No | Whether this is a FIFO queue |
| ContentBasedDeduplication | Boolean | No | Content-based deduplication for FIFO |
| KmsMasterKeyId | String | No | KMS key for encryption |
| KmsDataKeyReusePeriodSeconds | Integer | No | KMS key reuse period (60-86400) |
| Tags | List of Tag | No | Tags |
Example
Resources:
ProcessingQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-queue"
VisibilityTimeout: 300
MessageRetentionPeriod: 86400
RedrivePolicy:
deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn
maxReceiveCount: 5Attributes
| Attribute | Description |
|---|---|
| Arn | The ARN of the queue |
| QueueName | The name of the queue |
| QueueUrl | The URL of the queue |
AWS::SNS::Topic
Creates an SNS topic.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| TopicName | String | No | The name of the topic |
| DisplayName | String | No | The display name for the topic |
| Subscription | List of Subscription | No | The subscriptions |
| Tags | List of Tag | No | Tags |
| FifoTopic | Boolean | No | Whether this is a FIFO topic |
| ContentBasedDeduplication | Boolean | No | Content-based deduplication |
| KmsMasterKeyId | String | No | KMS key for encryption |
Example
Resources:
NotificationTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Sub "${AWS::StackName}-notifications"
DisplayName: "Notifications"
Subscription:
- Endpoint: !GetAtt LambdaFunction.Arn
Protocol: lambdaAttributes
| Attribute | Description |
|---|---|
| Arn | The ARN of the topic |
| TopicName | The name of the topic |
AWS::Events::Rule
Creates an EventBridge rule.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| Name | String | No | The name of the rule |
| Description | String | No | A description of the rule |
| State | String | No | The state (ENABLED or DISABLED) |
| ScheduleExpression | String | Cond | The schedule expression (rate or cron) |
| EventPattern | Json | Cond | The event pattern |
| EventBusName | String | No | The event bus name |
| RoleArn | String | No | The IAM role ARN |
| Targets | List of Target | No | The targets |
Example
Resources:
ScheduledRule:
Type: AWS::Events::Rule
Properties:
Name: !Sub "${AWS::StackName}-scheduler"
ScheduleExpression: "rate(5 minutes)"
State: ENABLED
Targets:
- Id: LambdaFunction
Arn: !GetAtt LambdaFunction.ArnAttributes
| Attribute | Description |
|---|---|
| Arn | The ARN of the rule |
AWS::CloudWatch::Alarm
Creates a CloudWatch alarm.
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| AlarmName | String | No | The name of the alarm |
| AlarmDescription | String | No | A description of the alarm |
| MetricName | String | Yes | The name of the metric |
| Namespace | String | Yes | The namespace of the metric |
| Dimensions | List of Dimension | No | The dimensions |
| Period | Integer | No | The period in seconds |
| EvaluationPeriods | Integer | No | Number of evaluation periods |
| Threshold | Double | Yes | The threshold value |
| ComparisonOperator | String | Yes | The comparison operator |
| Statistic | String | No | The statistic |
| ExtendedStatistic | String | Cond | The extended statistic |
| Unit | String | No | The unit |
| EvaluationPeriods | Integer | No | Number of evaluation periods |
| DatapointsToAlarm | Integer | No | Datapoints to trigger alarm |
| TreatMissingData | String | No | How to treat missing data |
| OKActions | List of String | No | Actions on OK state |
| AlarmActions | List of String | No | Actions on ALARM state |
| InsufficientDataActions | List of String | No | Actions on INSUFFICIENT_DATA |
Lambda Metrics Reference
| Metric | Description |
|---|---|
| Invocations | Number of invocations |
| Errors | Number of errors |
| Throttles | Number of throttles |
| Duration | Execution duration in ms |
| ConcurrentExecutions | Concurrent executions |
| ProvisionedConcurrentExecutions | Provisioned concurrent executions |
| ProvisionedConcurrencyInvocations | Provisioned concurrency invocations |
| ProvisionedConcurrencySpilloverInvocations | Spillover invocations |
| UnreservedConcurrentExecutions | Unreserved concurrent executions |
Example
Resources:
HighErrorRateAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub "${AWS::StackName}-high-error-rate"
AlarmDescription: Alert when error rate exceeds threshold
MetricName: Errors
Namespace: AWS/Lambda
Dimensions:
- Name: FunctionName
Value: !Ref LambdaFunction
Statistic: Sum
Period: 60
EvaluationPeriods: 5
Threshold: 10
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref AlertTopicIntrinsic Functions Reference
!Ref
Returns the value of the specified parameter or resource.
# Reference a parameter
FunctionName: !Ref FunctionNameParam
# Reference a resource (returns the physical ID)
FunctionArn: !Ref MyLambdaFunction!GetAtt
Returns the value of an attribute from a Lambda function.
# Get the function ARN
FunctionArn: !GetAtt MyLambdaFunction.Arn
# Get layer ARN
LayerArn: !GetAtt CommonLayer.Arn
# Get queue ARN
QueueArn: !GetAtt Queue.Arn!Sub
Substitutes variables in an input string.
# With variable substitution
FunctionName: !Sub ${AWS::StackName}-function
# With multiple variables
RoleArn: !Sub arn:aws:iam::${AWS::AccountId}:role/${RoleName}!ImportValue
Imports values exported by other stacks.
# Import from another stack
LambdaRoleArn: !ImportValue
Fn::Sub: "${NetworkStackName}-LambdaRoleArn"!FindInMap
Returns the value from a mapping.
# Find in mapping
RuntimeConfig: !FindInMap [RuntimeMap, !Ref Runtime, Config]!If
Returns one value if condition is true, another if false.
# Conditional environment variable
MemorySize: !If [IsProduction, 512, 256]IAM Policy Templates for Lambda
AWSLambdaBasicExecutionRole
Policies:
- AWSLambdaBasicExecutionRoleAWSLambdaVPCAccessExecutionRole
Policies:
- AWSLambdaVPCAccessExecutionRoleAWSLambdaSQSQueueExecutionRole
Policies:
- AWSLambdaSQSQueueExecutionRoleCustom Policy Document
Policies:
- PolicyName: LambdaPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
Resource: !Ref DataBucketArn
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
Resource: !Ref DataTableArnLambda Runtime Versions
| Runtime | Version | Architecture | Status |
|---|---|---|---|
| python | 3.13, 3.12, 3.11, 3.10, 3.9, 3.8 | x86_64, arm64 | Supported |
| nodejs | 22.x, 20.x, 18.x | x86_64, arm64 | Supported |
| java | 21, 17, 11 | x86_64, arm64 | Supported |
| go | 1.x | x86_64 | Supported |
| ruby | 3.3, 3.2 | x86_64, arm64 | Supported |
| provided | .al2023, .al2 | x86_64, arm64 | Supported |
| provided.al2 | .arm64 | arm64 | Supported |
Limits and Quotas
Lambda Limits
| Resource | Default Limit |
|---|---|
| Concurrent executions per account | 1,000 (configurable) |
| Function memory | 128-10,240 MB |
| Function timeout | 1-900 seconds |
| Deployment package size (zip) | 50 MB (direct), 250 MB (S3) |
| Container image size | 10 GB |
| Ephemeral storage (/tmp) | 512-10,240 MB |
| Layers | 5 layers per function |
| Variables | 4 KB total size |
API Gateway Limits
| Resource | Default Limit |
|---|---|
| Regional APIs per account | 600 |
| Stage variables per API | 100 |
| Timeout (REST API) | 29 seconds |
| Timeout (HTTP API) | 30 seconds |
Step Functions Limits
| Resource | Default Limit |
|---|---|
| Execution time | 1 year |
| State payload | 256 KB |
| Execution history | 25,000 events |
| Concurrent executions | 1,000 (standard), unlimited (express) |
Common Tags for Lambda
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Tags:
- Key: Environment
Value: !Ref Environment
- Key: Project
Value: !Ref ProjectName
- Key: Owner
Value: team@example.com
- Key: ManagedBy
Value: CloudFormation
- Key: CostCenter
Value: "12345"
- Key: Version
Value: "1.0.0"