Terraform archive_file归档Lambda文件报错:content需字符串类型
解决Terraform archive_file打包Lambda代码时的类型错误问题
问题原因
你遇到的错误是因为archive_file的content属性要求传入单个字符串(文件文本内容),但fileset函数返回的是文件路径列表,类型不匹配导致报错。要实现将library文件夹和指定Lambda handler文件打包,需要使用source_files或source_dir属性来指定要归档的文件,而非content。
文件夹结构示例
假设你的项目结构如下:
project-root/ ├── library/ │ ├── utils.py │ ├── common_classes.py │ └── helpers/ │ └── db_helper.py ├── lambda1_handler.py └── main.tf
正确配置方案
方案1:使用source_files合并handler和library文件
通过concat将handler文件路径与fileset生成的library文件路径列表合并,直接指定所有要打包的文件:
data "archive_file" "lambda1_zip" { type = "zip" output_path = "${path.module}/lambda1.zip" source_files = concat( // 加入Lambda handler文件 ["${path.module}/lambda1_handler.py"], // 递归加入library下的所有文件,保留目录结构 [for file_path in fileset("${path.module}/library", "**/*") : "${path.module}/library/${file_path}"] ) }
方案2:使用source_dir配合includes筛选文件
将项目根目录作为源目录,通过includes指定需要打包的文件(handler和library下的所有文件):
data "archive_file" "lambda1_zip" { type = "zip" output_path = "${path.module}/lambda1.zip" source_dir = "${path.module}" includes = concat( ["lambda1_handler.py"], [for file_path in fileset("${path.module}/library", "**/*") : "library/${file_path}"] ) }
关键注意事项
- 打包后的zip结构会保留原目录关系:handler文件在zip根目录,
library文件夹也在根目录,这样Lambda执行时可以直接通过import library.utils引用共用类。 fileset("${path.module}/library", "**/*")会递归匹配library下的所有文件(包括子目录中的文件),满足多文件归档需求。- 当文件内容或路径变化时,Terraform会自动重新生成zip文件,无需手动操作。
内容的提问来源于stack exchange,提问作者K P
相关产品推荐
相关产品推荐

