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

CloudFormation中Lambda内联Python代码引用参数失败问题

问题解答

直接在Lambda内联Python代码里写${OpsBucketName}语法是错误的,因为CloudFormation不会自动解析Lambda的ZipFile字符串内容里的变量,必须通过Fn::Sub函数显式完成参数值的替换。

以下是完整的CloudFormation模板示例,包含参数定义、Lambda资源(正确引用参数)、必要的IAM权限:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  OpsBucketName:
    Type: String
    Description: Name of the S3 bucket storing the Cognito logo
Resources:
  CognitoLogoLambda:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.lambda_handler
      Runtime: python3.11
      Role: !GetAtt LambdaExecutionRole.Arn
      # 使用Fn::Sub替换代码中的参数变量
      Code:
        ZipFile: !Sub |
          import boto3
          import json

          s3 = boto3.client('s3')
          # 这里的${OpsBucketName}会被Sub替换为实际的参数值
          BUCKET_NAME = "${OpsBucketName}"
          LOGO_KEY = "cognito-logo.png" # 替换为你的Logo文件键名

          def lambda_handler(event, context):
              try:
                  # 从S3获取Logo文件
                  response = s3.get_object(Bucket=BUCKET_NAME, Key=LOGO_KEY)
                  logo_content = response['Body'].read()
                  # 后续处理:比如返回给Cognito自定义页面的逻辑
                  return {
                      'statusCode': 200,
                      'body': json.dumps('Logo fetched successfully')
                  }
              except Exception as e:
                  print(f"Error fetching logo: {str(e)}")
                  return {
                      'statusCode': 500,
                      'body': json.dumps('Failed to fetch logo')
                  }
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: S3ReadAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: s3:GetObject
                Resource: !Sub "arn:aws:s3:::${OpsBucketName}/*"

关键说明:

  • 必须用!Sub(或Fn::Sub的完整写法)包裹ZipFile的代码内容,这样CloudFormation才会识别并替换代码中的${OpsBucketName}变量为参数的实际值。
  • 注意代码字符串的引号处理:示例中用|保留多行格式,外层是CloudFormation的YAML字符串,内部Python代码用单引号或转义双引号,避免语法冲突。
  • 要给Lambda的执行角色添加S3读取权限,确保它能访问指定的桶和文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 23:32:36