mcpField
A
aws-cloudformation-lambda

aws-cloudformation-lambda

github.com/giuseppe-trisciuoglio云与 DevOps36567 次安装7 周前更新
代码仓库

关于 aws-cloudformation-lambda

面向使用 CloudFormation 构建 AWS Lambda 的开发者,提供函数、触发器与周边资源的模板配置及部署验证流程。涵盖监控、版本、权限和可靠性设置。

主要功能

  1. 01定义函数参数与配置
  2. 02配置事件源和 API Gateway
  3. 03设置 IAM 角色与最小权限
  4. 04配置监控、版本和别名
  5. 05验证、部署并检查堆栈

适用场景

  1. 01通过 CloudFormation 部署 Lambda
  2. 02为 S3、SQS 等事件配置触发器
  3. 03将 Lambda 接入 API Gateway

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill aws-cloudformation-lambda

安装后在 Claude Code 中输入/aws-cloudformation-lambda确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
constraints.md
examples.md
reference.md

详细介绍

AWS CloudFormation Lambda 函数

概述

使用 CloudFormation 模板和验证、部署工作流,创建可用于生产环境的 Lambda 函数。

适用场景

  • 使用 CloudFormation 创建 Lambda 函数
  • 配置事件源(S3、SQS、DynamoDB、Kinesis)
  • 实现 Lambda 层并优化冷启动
  • 将 Lambda 与 API Gateway 集成
  • 通过验证部署 Lambda 基础设施

部署工作流

始终遵循以下部署工作流:

1. 验证模板
aws cloudformation validate-template --template-body file://template.yaml
2. 部署堆栈
aws cloudformation deploy \
  --template-file template.yaml \
  --stack-name my-lambda-stack \
  --capabilities CAPABILITY_IAM \
  --parameter-overrides Environment=prod
3. 监控堆栈事件
aws cloudformation describe-stack-events \
  --stack-name my-lambda-stack \
  --query 'StackEvents[?ResourceStatus==`CREATE_FAILED`||ResourceStatus==`UPDATE_FAILED`]'
4. 验证资源
aws lambda get-function --function-name my-lambda-stack-function
aws cloudformation describe-stacks --stack-name my-lambda-stack \
  --query 'Stacks[0].StackStatus'
5. 失败时回滚
aws cloudformation delete-stack --stack-name my-lambda-stack
aws logs describe-log-groups --log-group-name-prefix "/aws/lambda/my-lambda"

说明

按照以下步骤使用 CloudFormation 创建 Lambda 函数:

1. 定义 Lambda 函数参数

指定运行时、内存、超时和环境变量:

Parameters:
  FunctionMemory:
    Type: Number
    Default: 256
    AllowedValues:
      - 128
      - 256
      - 512
      - 1024
      - 2048
    Description: Lambda function memory in MB

  FunctionTimeout:
    Type: Number
    Default: 30
    MinValue: 1
    MaxValue: 900
    Description: Function timeout in seconds

  Runtime:
    Type: String
    Default: nodejs20.x
    AllowedValues:
      - nodejs20.x
      - python3.11
      - java21
      - dotnet8
      - go1.x
    Description: Lambda runtime environment
2. 创建 Lambda 函数

定义基本的函数配置:

Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub "${AWS::StackName}-function"
      Runtime: !Ref Runtime
      Handler: index.handler
      Role: !Ref ExecutionRole
      MemorySize: !Ref FunctionMemory
      Timeout: !Ref FunctionTimeout
      Code:
        S3Bucket: !Ref CodeBucket
        S3Key: !Ref CodeKey
      Environment:
        Variables:
          LOG_LEVEL: INFO
          DATABASE_URL: !Ref DatabaseUrl
      Tags:
        - Key: Environment
          Value: !Ref Environment
3. 配置执行角色

应用最小权限 IAM 策略:

Resources:
  ExecutionRole:
    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: S3ReadAccess
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:GetObject
                Resource: !Sub "${DataBucket.Arn}/*"
4. 添加事件源

配置用于触发 Lambda 调用的事件源:

Resources:
  # S3 event source
  S3EventSource:
    Type: AWS::Lambda::EventSourceMapping
    Properties:
      EventSourceArn: !GetAtt DataBucket.Arn
      FunctionName: !Ref LambdaFunction

  # SQS event source
  SQSEventSource:
    Type: AWS::Lambda::EventSourceMapping
    Properties:
      EventSourceArn: !GetAtt Queue.Arn
      FunctionName: !Ref LambdaFunction
      BatchSize: 10
      MaximumBatchingWindowInSeconds: 5
5. 配置 API Gateway 集成

设置 REST 或 HTTP API 集成:

Resources:
  # HTTP API integration
  HttpApi:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: !Sub "${AWS::StackName}-api"
      ProtocolType: HTTP
      Target: !Ref LambdaFunction

  ApiIntegration:
    Type: AWS::ApiGatewayV2::Integration
    Properties:
      ApiId: !Ref HttpApi
      IntegrationType: AWS_PROXY
      IntegrationUri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations"
6. 实现版本控制和别名

创建函数版本和别名:

Resources:
  LambdaVersion:
    Type: AWS::Lambda::Version
    Properties:
      FunctionName: !Ref LambdaFunction
      Description: !Sub "Version ${AWS::StackName} v1"

  LambdaAlias:
    Type: AWS::Lambda::Alias
    Properties:
      FunctionName: !Ref LambdaFunction
      FunctionVersion: !GetAtt LambdaVersion.Version
      Name: live
7. 配置监控

启用 CloudWatch 日志和 X-Ray 跟踪:

Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      LoggingConfig:
        LogGroup: !Ref LogGroup
      TracingConfig:
        Mode: Active

  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub "/aws/lambda/${LambdaFunction}"
      RetentionInDays: 7
8. 设置死信队列

为调用失败配置 DLQ:

Resources:
  DeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "${AWS::StackName}-dlq"

  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      DeadLetterConfig:
        TargetArn: !GetAtt DeadLetterQueue.Arn

示例

完整的 Lambda 堆栈模板
AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda function with monitoring and DLQ

Parameters:
  FunctionMemory:
    Type: Number
    Default: 256
    AllowedValues: [128, 256, 512, 1024]
  FunctionTimeout:
    Type: Number
    Default: 30

Resources:
  ExecutionRole:
    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

  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub "${AWS::StackName}-function"
      Runtime: nodejs20.x
      Handler: index.handler
      Role: !GetAtt ExecutionRole.Arn
      MemorySize: !Ref FunctionMemory
      Timeout: !Ref FunctionTimeout
      Code:
        S3Bucket: !Ref CodeBucket
        S3Key: !Ref CodeKey
      Environment:
        Variables:
          LOG_LEVEL: INFO

  LambdaVersion:
    Type: AWS::Lambda::Version
    Properties:
      FunctionName: !Ref LambdaFunction

  LambdaAlias:
    Type: AWS::Lambda::Alias
    Properties:
      FunctionName: !Ref LambdaFunction
      FunctionVersion: !GetAtt LambdaVersion.Version
      Name: live

Outputs:
  FunctionArn:
    Value: !GetAtt LambdaFunction.Arn
  FunctionName:
    Value: !Ref LambdaFunction

最佳实践

性能优化
  • 对 Java 函数使用 SnapStart,以消除冷启动
  • 对需要低延迟的关键函数使用预置并发
  • 保持部署包较小(压缩后小于 50 MB)
  • 根据函数需求优化内存大小
  • 使用合适的超时值(避免使用最大超时值)
  • 配置预留并发以防止节流
成本优化
  • 合理设置内存分配,以提高成本效益
  • 有策略地使用预置并发(空闲时会产生额外成本)
  • 监控 Lambda 执行时长并进行优化,以加快执行速度
  • 高效使用临时存储空间(/tmp)
  • 清理未使用的 Lambda 函数和版本
  • 考虑使用 Lambda PowerTuning 优化内存和功率配置
安全性
  • 为执行角色应用最小权限 IAM 策略
  • 对静态存储的环境变量进行加密
  • 使用 VPC 端点私密访问 AWS 服务
  • 定期轮换 IAM 凭证
  • 配置 VPC,以便私密访问函数
  • 使用 AWS KMS 加密敏感数据
可靠性
  • 为异步调用配置死信队列
  • 使用指数退避实现重试逻辑
  • 使用 CloudWatch 警报监控错误
  • 在部署前全面测试 Lambda 函数
  • 为下游服务故障实现断路器
  • 使用 Lambda 别名进行金丝雀部署
监控和可观测性
  • 为所有函数启用 CloudWatch Logs
  • 使用 X-Ray 进行分布式跟踪
  • 配置 CloudWatch 指标以监控性能
  • 设置错误、节流和执行时长警报
  • 使用 Lambda Insights 进行调试
  • 监控并发执行和节流情况
版本控制和部署
  • 在生产环境中使用 Lambda 别名(live、staging)
  • 使用加权别名实现渐进式部署
  • 创建函数版本以实现不可变部署
  • 使用 SAM 或 AWS CDK 简化 Lambda 部署
  • 使用 Lambda 别名实现蓝绿部署
  • 首先在开发环境中测试函数更改

限制和警告

  • 超时限制:Lambda 超时时间最长为 900 秒(15 分钟);请设置适当的值,以避免产生孤立的执行
  • 部署包大小:压缩包最大为 50 MB,解压后最大为 250 MB(包括层)
  • 层限制:每个函数最多 5 个层;每个层解压后最大为 50 MB
  • 环境变量:所有变量总计最多 4 KB;请使用 KMS 加密敏感值
  • 冷启动:Java 和 .NET 函数的冷启动时间较长;对于对延迟敏感的工作负载,请使用 SnapStart 或 Provisioned Concurrency
  • 并发执行:每个区域的默认限额为 1000;对于高流量函数,请申请提高限额
  • VPC 网络:VPC 中的 Lambda 在首次调用时会增加 10-30 秒的冷启动开销
  • IAM 权限:切勿在 Resource 策略中使用 *;始终将范围限定为特定资源
  • 死信队列:异步调用必须配置死信队列;确保死信队列与函数位于同一区域
  • 成本监控:启用账单提醒;Lambda 按调用次数和执行时长收费

参考资料

如需详细的实现指南,请参阅:

  • constraints.md - 资源限制(函数限额、并发执行、超时、内存)、部署限制(函数大小、层大小、环境变量)、运维限制(冷启动、VPC 网络、事件源、DLQ)、安全限制(执行角色、资源策略、VPC 端点)、成本考量(预置并发、执行时长、内存、数据传输)以及性能限制(SnapStart、层版本管理、X-Ray 跟踪、异步调用)

相关资源

评论

支持 Markdown