从S3获取Zip包至AWS Lambda Function构造报错求助
AWS CDK Lambda引用S3部署Zip包出现NoSuchKey错误
使用AWS CDK通过S3 Deploy将Lambda代码打包为Zip包部署到指定S3桶,后续Lambda引用该Zip对象时触发错误:
Error occurred while GetObject. S3 Error Code: NoSuchKey. S3 Error Message: The specified key does not exist.
尝试将S3桶创建和部署移至独立堆栈,导出后导入Lambda堆栈,控制台能看到桶和Zip包哈希值,但错误依旧。
附当前代码:
export class LambdaStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // Define the S3 bucket for deployment const deploymentBucket = new s3.Bucket(this, 'DeploymentBucket', { bucketName: 'test-deployment-bucket-100', versioned: true, }); // Deploy the Lambda function code to the S3 bucket const deployment = new s3deploy.BucketDeployment(this, 'DeployLambdaCode', { sources: [s3deploy.Source.asset(path.join(__dirname, '../lambda/test'))], destinationBucket: deploymentBucket, //destinationKeyPrefix: '', extract: false, }); // Define the Lambda function const lambdaFunction = new lambda.Function(this, 'LambdaFunction', { runtime: lambda.Runtime.NODEJS_18_X, //pick up lambda code from the S3 bucket code: lambda.Code.fromBucket(deployment.deployedBucket, cdk.Fn.select(0, deployment.objectKeys)), handler: 'index.handler', }); // Add dependency to wait for the S3 deployment to complete lambdaFunction.node.addDependency(deploymentBucket); } }
问题修复方案
1. 修正依赖关系
你当前给Lambda添加的依赖是S3桶对象,但实际需要依赖的是S3部署操作,确保Lambda在代码上传完成后再创建。
2. 简化对象键引用
无需手动使用cdk.Fn.select(0, deployment.objectKeys)获取对象键,CDK提供了deployment.deployedObjectKey属性,能直接、可靠地获取部署后的Zip包对象键。
修改后的代码:
export class LambdaStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // Define the S3 bucket for deployment const deploymentBucket = new s3.Bucket(this, 'DeploymentBucket', { bucketName: 'test-deployment-bucket-100', versioned: true, }); // Deploy the Lambda function code to the S3 bucket const deployment = new s3deploy.BucketDeployment(this, 'DeployLambdaCode', { sources: [s3deploy.Source.asset(path.join(__dirname, '../lambda/test'))], destinationBucket: deploymentBucket, extract: false, }); // Define the Lambda function const lambdaFunction = new lambda.Function(this, 'LambdaFunction', { runtime: lambda.Runtime.NODEJS_18_X, // 使用deployedObjectKey直接获取部署后的对象键 code: lambda.Code.fromBucket(deployment.deployedBucket, deployment.deployedObjectKey), handler: 'index.handler', }); // 修正依赖:等待S3部署完成后再创建Lambda lambdaFunction.node.addDependency(deployment); } }
额外排查点
- 确认
../lambda/test路径下存在有效代码文件,CDK打包时能正确生成Zip包 - 若使用跨堆栈部署,确保导出的是
deployment.deployedBucket.bucketName和deployment.deployedObjectKey,而非手动拼接哈希值 - 桶开启版本控制时,CDK会自动处理版本化场景下的对象引用,无需手动指定版本ID
内容的提问来源于stack exchange,提问作者Notiq Olusesi
相关产品推荐
相关产品推荐

