由于客户函数错误,Lambda 执行失败,状态为 200:无法导入模块"lambda_function"



我有一个lambda函数,它通过Codepipeline部署在cloudFormation中。

我的文件夹结构如下所示:

LambdaCode/
lambda_function.py
samTemplate.yml
buildspec.yml

lambda_function.py

import json
def lambda_handler(event, context):
response = "Hello from lambda"
return {"statusCode": 200, "body": json.dumps(response)}

samTemplate如下,

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: CD Demo Lambda
Resources:
CDDemoLambda:
Type: 'AWS::Serverless::Function'
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.6
CodeUri: s3://<bkt-name>/LambdaCode.zip
Description: 'Lambda function for CD Demo'
MemorySize: 128
Timeout: 30
Events:
getAZsAPI:
Type: Api
Properties:
Path: /getpage
Method: get
Environment:
Variables:
REGION: <region>

buildspec.yml

version: 0.1
phases:
install:
commands:
- aws cloudformation package --template-file samTemplate.yaml --s3-bucket artifact-store-s3 --output-template-file outputSamTemplate.yaml
artifacts:
type: zip
files:
- samTemplate.yaml
- outputSamTemplate.yaml

在代码管道部署阶段,当我将CodeUri设置为时,我遇到了一个错误/LambdaCode,因此我将LambdaCode作为zip上传到s3 bucket中,并将s3 URI作为Codeuri。管道在那之后成功运行,但在API网关中,当我尝试访问部署的URL时,我在cloudwatch:中得到了错误

Lambda execution failed with status 200 due to customer function error: Unable to import module 'lambda_function'. 

部署无法调用lambda_function。原因可能是什么?由于我使用的是s3URI,是否需要修改lambda处理程序?

检查zip的内容,主要错误是找不到文件或处理程序。

我建议您使用命令SAM.来打包您的lambda

示例:

sam package --region eu-west-1 --template-file .sam-template.yml --s3-bucket artifact-bucket --output-template-file packaged.yml

在sam模板中,您将代码的位置放在本地:

LoginFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: 'usr-api-login-function'
CodeUri: ./dist/user-login-function
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref TableName
Events:
SearchPost:
Type: Api
Properties:
RestApiId: !Ref ApiGateway
Path: /user/login
Method: POST

之后你可以部署它

sam deploy --region eu-west-1 --template-file packaged.yml --stack-name name-stack --capabilities CAPABILITY_IAM

相关内容

最新更新