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

求助:如何通过CloudFormation向Lambda Python代码传递目标桶参数

解决CloudFormation参数传递到Lambda Python代码的问题

我来帮你搞定这个S3复制Lambda的参数传递难题——核心思路是利用Lambda的环境变量来传递CloudFormation中的dstBucket参数,这是AWS官方推荐的配置化传递方式,比硬编码灵活太多了。

步骤1:修改CloudFormation模板,为Lambda注入环境变量

在你的Lambda资源定义里,新增Environment配置块,把dstBucket参数通过Ref注入到Lambda的环境变量中。示例如下:

Resources:
  S3CopyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.lambda_handler
      Runtime: python3.11
      Code:
        # 这里替换成你的Lambda代码存储位置,比如S3桶路径或内嵌代码
        S3Bucket: !Ref LambdaCodeBucket
        S3Key: !Ref LambdaCodeKey
      Environment:
        Variables:
          TARGET_BUCKET: !Ref dstBucket  # 把CloudFormation参数传给Lambda环境变量
      # 别忘了配置Lambda执行角色、内存、超时等必要属性
      Role: !Ref LambdaExecutionRole

步骤2:修改Python代码,读取环境变量

把原来硬编码的target_bucket替换成读取Lambda的环境变量,这样就能动态获取CloudFormation传入的目标桶名称了:

import os
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # 从环境变量中读取目标桶
    target_bucket = os.environ['TARGET_BUCKET']
    
    # 处理S3复制逻辑(示例)
    for record in event['Records']:
        source_bucket = record['s3']['bucket']['name']
        source_key = record['s3']['object']['key']
        
        # 执行复制操作
        copy_source = {'Bucket': source_bucket, 'Key': source_key}
        s3.copy_object(CopySource=copy_source, Bucket=target_bucket, Key=source_key)
    
    return {
        'statusCode': 200,
        'body': f'Successfully copied objects to {target_bucket}'
    }

为什么之前的尝试可能失败?

  • 如果你之前想直接在Lambda代码里用Ref,那肯定行不通——Ref是CloudFormation的模板专属函数,只能在CloudFormation模板解析阶段生效,Lambda代码是运行时执行的,根本识别不了CloudFormation的模板语法。
  • 环境变量是CloudFormation和Lambda之间传递配置的标准通道,CloudFormation会在创建/更新Lambda时把变量注入进去,运行时Lambda可以直接读取。

额外注意事项

  • 一定要确保你的Lambda执行角色拥有目标桶的访问权限(比如s3:PutObject权限),否则复制操作会报错。
  • 确认dstBucket参数在CloudFormation模板中定义正确,示例参数定义:
Parameters:
  dstBucket:
    Type: String
    Description: Target S3 bucket for replication

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:13:38