Terraform模块中${path.module}路径异常,Lambda找不到ZIP文件如何解决?
问题分析与解决方案
问题根源
你最初的错误是因为output_path使用了相对路径./files/example.zip,这个路径是相对于项目工作目录(即执行terraform apply的目录,也就是项目的terraform目录),而非模块自身的目录,导致Terraform在项目的files目录下找不到生成的ZIP文件。
修改后使用${path.module}/files/example.zip是正确方向,但你误解了路径指向:path.module是Terraform内置变量,代表当前模块的根目录(在项目中对应.terraform/modules/my_example_module),archive_file会自动在这个路径下生成ZIP文件——该文件是Terraform执行时动态生成的,无需提前在模块仓库中创建。
正确实现方式
模块代码调整
确保archive_file的output_path和templatefile路径都使用path.module,保证路径始终指向模块自身目录:
data "archive_file" "example" { type = "zip" output_path = "${path.module}/files/example.zip" source { content = templatefile("${path.module}/files/example.py", {}) filename = "example.py" } } resource "aws_lambda_function" "example_lambda" { filename = data.archive_file.example.output_path source_code_hash = data.archive_file.example.output_base64sha256 # 其他必要参数... }
关键说明
path.module的作用:无论模块被引用到哪个项目,该变量都会指向模块被下载后的目录(项目的.terraform/modules/[模块名]),确保路径一致性。- ZIP文件生成:
archive_file在执行terraform apply时,会自动在output_path指定位置生成ZIP文件。只要模块仓库中存在files目录(已有example.py),就不会出现目录不存在的问题。 - Lambda路径引用:
aws_lambda_function的filename直接引用data.archive_file.example.output_path即可,Terraform会从项目工作上下文正确访问.terraform/modules/my_example_module/files/example.zip路径。
额外兜底处理
如果模块的files目录可能动态生成(比如部分场景下目录不存在),可以添加null_resource确保目录存在:
resource "null_resource" "create_files_dir" { provisioner "local-exec" { command = "mkdir -p ${path.module}/files" } } data "archive_file" "example" { depends_on = [null_resource.create_files_dir] type = "zip" output_path = "${path.module}/files/example.zip" source { content = templatefile("${path.module}/files/example.py", {}) filename = "example.py" } }
内容的提问来源于stack exchange,提问作者polo
相关产品推荐
相关产品推荐

