AWS::Serverless::Function使用InlineCode属性失效问题排查
解决SAM CLI本地启动内联Lambda函数时的NoneType错误
我尝试用SAM CLI创建内联Lambda函数,对应的YAML模板如下:
HealthFunction: Type: 'AWS::Serverless::Function' Properties: PackageType: Zip Runtime: nodejs20.x Handler: index.handler InlineCode: | export const handler = (event) => { return { statusCode: 200 }; } Timeout: 30 Description: 'Health Lambda function' Events: Api: Type: HttpApi Properties: ApiId: !Ref AwsApiGateway Path: /health Method: GET
运行sam local start-api命令后出现错误:
Initializing the lambda functions containers. Lambda functions containers initialization failed because of expected str, bytes or os.PathLike object, not NoneType Error: Lambda functions containers initialization failed
根据AWS官方文档,使用InlineCode时可以留空CodeUri,但实际运行却报错,请问问题出在哪里?
问题原因
SAM CLI的本地容器初始化逻辑存在兼容性问题——虽然CloudFormation允许使用InlineCode时省略CodeUri,但本地模拟时SAM需要CodeUri为一个有效的字符串类型路径(哪怕是空目录或空字符串),否则会因获取到NoneType值抛出错误。
解决方法
方法1:显式指定CodeUri
在函数的Properties中添加CodeUri属性,设置为本地存在的路径(比如当前目录./),即使目录为空也可以:
HealthFunction: Type: 'AWS::Serverless::Function' Properties: PackageType: Zip Runtime: nodejs20.x Handler: index.handler CodeUri: ./ # 显式指定本地路径 InlineCode: | export const handler = (event) => { return { statusCode: 200 }; } Timeout: 30 Description: 'Health Lambda function' Events: Api: Type: HttpApi Properties: ApiId: !Ref AwsApiGateway Path: /health Method: GET
也可以直接设置为空字符串CodeUri: '',部分SAM CLI版本支持这种写法。
方法2:升级SAM CLI到最新版本
这个问题可能是旧版本SAM CLI的兼容性bug,升级到最新版本可能修复:
# 查看当前版本 sam --version # 升级SAM CLI sam update
内容的提问来源于stack exchange,提问作者Tal Rofe
相关产品推荐
相关产品推荐

