You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询CloudFormation中调用自定义Lambda函数的最简实现方案

CloudFormation Lambda自定义资源最简实现指南

没问题,我来给你拆解下怎么用CloudFormation调用你的Lambda函数作为自定义资源,全程最简实现,一步一步来:

核心原理先搞懂

CloudFormation自定义资源要求Lambda函数必须返回符合CFN规范的响应格式,而不是你现在的简单message。这个响应得包含请求状态(成功/失败)、物理资源ID,还有你要返回的数据。另外,Lambda得能接收CFN发送的事件(包含Create/Update/Delete动作、响应URL等),并把结果发回给CFN。

第一步:调整你的Lambda函数

你原来的函数得改成适配CFN自定义资源的格式,AWS提供了cfnresponse模块可以直接用,省得自己写HTTP请求。修改后的代码如下:

import cfnresponse

def my_handler(event, context):
    # 先处理CFN的事件类型(Create/Update/Delete)
    try:
        # 从事件里拿你需要的参数(这里用first_name和last_name举例)
        first_name = event['ResourceProperties']['first_name']
        last_name = event['ResourceProperties']['last_name']
        message = f'Hello {first_name} {last_name}!'
        
        # 构造要返回给CFN的数据
        response_data = {'message': message}
        
        # 发送成功响应给CFN
        cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
    except Exception as e:
        # 出错的话发送失败响应,带上错误信息
        cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})

注意:cfnresponse是AWS Lambda内置的模块,不需要额外安装依赖,直接用就行。

第二步:编写CloudFormation模板

模板里要包含三个核心部分:Lambda执行角色、Lambda函数本身、自定义资源。下面是最简版本:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  # 1. Lambda执行角色:允许Lambda写日志,以及和CFN交互
  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

  # 2. Lambda函数:把刚才修改后的代码放进来
  MyCustomResourceLambda:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.my_handler
      Runtime: python3.12
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        ZipFile: |
          import cfnresponse

          def my_handler(event, context):
              try:
                  first_name = event['ResourceProperties']['first_name']
                  last_name = event['ResourceProperties']['last_name']
                  message = f'Hello {first_name} {last_name}!'
                  response_data = {'message': message}
                  cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
              except Exception as e:
                  cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})

  # 3. 自定义资源:调用上面的Lambda
  MyCustomResource:
    Type: Custom::MyGreetingResource
    Properties:
      ServiceToken: !GetAtt MyCustomResourceLambda.Arn
      # 这里传你要给Lambda的参数,对应event['ResourceProperties']
      first_name: John
      last_name: Doe

# 可选:输出自定义资源返回的message
Outputs:
  GreetingMessage:
    Value: !GetAtt MyCustomResource.message

第三步:测试验证

  1. 把上面的模板保存为custom-resource.yaml
  2. 用AWS CLI部署:aws cloudformation deploy --stack-name MyCustomResourceStack --template-file custom-resource.yaml
  3. 部署完成后,查看Stack的输出,就能看到Hello John Doe!的结果了
  4. 也可以去Lambda控制台查看日志,确认函数执行正常

关键细节提醒

  • 自定义资源的Type可以随便命名,格式是Custom::XXX就行
  • ServiceToken必须严格指向Lambda函数的ARN,这是CFN调用Lambda的关键
  • 如果需要处理Update/Delete动作,只需要在Lambda函数里判断event['RequestType']即可,比如Delete动作可以直接返回SUCCESS,不需要额外处理
  • 物理资源ID(PhysicalResourceId)默认由cfnresponse用RequestId填充,如果你需要固定值,可以在send方法里指定:cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, physical_resource_id='MyFixedId')

内容的提问来源于stack exchange,提问作者Rudziankoŭ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:52:33