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

如何在CloudFormation Output中引用Lambda响应数据以实现跨栈引用?

如何将Custom Resource Lambda返回的数据引用到CloudFormation Output中

首先,你之前的写法有误——Lambda函数本身不会直接暴露response_data作为可引用的属性,真正承载返回数据的是你定义的Custom::EC2CustomResource资源。CloudFormation会把Lambda通过cfnresponse.send返回的response_data中的键,作为Custom Resource的可查询属性,你需要通过这个Custom Resource来获取值。

正确的Output配置方式

修改你的Outputs部分,将引用对象从AWSLambdaFunction改为EC2CustomResource,并直接引用response_data里的testList键:

Outputs:
  LambdaFunctionOutput:
    Value: !GetAtt EC2CustomResource.testList
    Description: Return Value of Lambda Function from Custom Resource
    # 如果需要跨栈引用,添加Export字段
    Export:
      Name: !Sub '${AWS::StackName}-TestList'

为什么之前的写法不生效?

  • AWS::Lambda::Function资源的!GetAtt只能获取Lambda本身的属性(比如Arn、FunctionName等),它不知道你在函数代码里返回的response_data内容。
  • 当你创建Custom::EC2CustomResource时,CloudFormation会调用指定的Lambda函数,并将Lambda返回的response_data中的键值对注册为该Custom Resource的自定义属性,你才能通过!GetAtt来访问这些值。

完整的示例代码(包含正确的Output)

Resources:
  EC2CustomResource:
    Type: Custom::EC2CustomResource
    Properties:
      ServiceToken: !GetAtt AWSLambdaFunction.Arn
  AWSLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Description: "bucket!"
      FunctionName: !Sub '${AWS::StackName}-${AWS::Region}-lambda'
      Handler: index.handler
      Timeout: 360
      Runtime: python3.9
      Code:
        ZipFile: |
          import boto3
          import cfnresponse
          def handler(event, context):
            response_data = {}
            s3 = boto3.client('s3')
            # dummy test
            testList = [1, 2, 3]
            try:
              print("Execution succesfull!")
              response_data['testList'] = testList
              cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
            except Exception as e:
              print("Execution failed...")
              response_data['Error'] = str(e)
              cfnresponse.send(event, context, cfnresponse.FAILED, response_data)

Outputs:
  LambdaFunctionOutput:
    Value: !GetAtt EC2CustomResource.testList
    Description: Return Value of Lambda Function from Custom Resource
    Export:
      Name: !Sub '${AWS::StackName}-TestList'

跨栈引用的使用方法

在其他需要引用这个值的CloudFormation栈中,可以使用!ImportValue来获取:

# 其他栈的资源或Output中引用
SomeResource:
  Type: AWS::Some::Resource
  Properties:
    SomeProperty: !ImportValue 'SourceStackName-TestList'

注意事项

  • 确保Custom Resource的创建状态为CREATE_COMPLETE,如果Lambda返回FAILED状态,Custom Resource会创建失败,对应的属性也无法获取。
  • response_data中的键名需要符合CloudFormation属性命名规则(允许字母、数字、下划线和连字符,不能以数字开头)。
  • 如果返回的是复杂类型(比如列表、字典),CloudFormation会将其序列化为字符串,跨栈引用时会保持这个序列化后的格式,你可能需要在接收方的代码中解析它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:12:37