为何每次执行sam package都会上传构件?求解决方法
解决SAM Package重复上传Lambda构件的问题
SAM默认不管本地代码变没变,每次跑sam package都会重新打包上传Lambda包,要实现像流水线那样的「跳过已存在包」逻辑,核心是用本地代码的哈希值和S3对象做校验,具体步骤如下:
1. 给Lambda代码生成唯一哈希
要保证代码内容、结构、文件名完全一致时哈希才相同,得递归计算目录下所有文件的哈希并排序后再生成总哈希:
Linux/macOS 命令
# 替换成你的Lambda代码目录路径,排除临时文件(比如__pycache__) find ./your-lambda-dir -type f -not -path "*/__pycache__/*" -exec sha256sum {} \; | sort -k 2 | sha256sum | awk '{print $1}'
Windows PowerShell 命令
# 替换成你的Lambda代码目录路径 $hashList = Get-ChildItem -Path ./your-lambda-dir -Recurse -File | Where-Object { $_.FullName -notmatch "__pycache__" } | Get-FileHash | Select-Object Hash, Path | Sort-Object Path $combinedHash = ($hashList.Hash | Out-String).Trim() | Get-FileHash | Select-Object -ExpandProperty Hash
2. 把哈希作为S3路径前缀
每次打包前先算好哈希,用哈希值作为S3存储路径的一部分,这样只要代码没变,哈希就不变,SAM会自动检测到S3上已有对应包,跳过上传:
# 计算哈希 SAM_HASH=$(find ./your-lambda-dir -type f -not -path "*/__pycache__/*" -exec sha256sum {} \; | sort -k 2 | sha256sum | awk '{print $1}') # 运行sam package,指定带哈希的前缀 sam package --template-file template.yaml --s3-bucket your-s3-bucket --s3-prefix "lambda-packages/${SAM_HASH}" --output-template-file packaged.yaml
3. 多Lambda函数的处理方式
针对多个Lambda的本地CodeUri,给每个函数单独算哈希,分别同步到对应哈希路径的S3位置,再让SAM指向这些路径:
# 给func1计算哈希并同步到S3 FUNC1_HASH=$(find ./func1 -type f -not -path "*/__pycache__/*" -exec sha256sum {} \; | sort -k 2 | sha256sum | awk '{print $1}') aws s3 sync ./func1 s3://your-s3-bucket/lambda-packages/func1/${FUNC1_HASH} --delete # 给func2计算哈希并同步到S3 FUNC2_HASH=$(find ./func2 -type f -not -path "*/__pycache__/*" -exec sha256sum {} \; | sort -k 2 | sha256sum | awk '{print $1}') aws s3 sync ./func2 s3://your-s3-bucket/lambda-packages/func2/${FUNC2_HASH} --delete # 修改模板里的CodeUri为对应的S3路径,再运行sam package(此时SAM会跳过上传) sam package --template-file template.yaml --s3-bucket your-s3-bucket --output-template-file packaged.yaml
关键注意点
- 一定要过滤临时文件(比如Python的
__pycache__、Node的node_modules/.cache),不然这些文件的变化会导致哈希无效,白跑上传流程。 - 如果用SAM的容器打包(
--use-container),要确保容器内的依赖包也参与哈希计算,避免本地和容器内依赖不一致导致哈希偏差。
内容的提问来源于stack exchange,提问作者Amonicasei
相关产品推荐
相关产品推荐

