为 lambda_module 计算预构建 ZIP 文件的源代码哈希?

compute source code hash on pre-built ZIP file for lambda_module?

我已经编写了一个 terraform 模块来创建 Lambda,但我无法弄清楚如何在预构建的 ZIP 文件上计算 source_code_hash。这将在管道中进行,因此每次都会构建 ZIP 文件,并且在我到达 terraform 步骤之前可能会有所不同。
我正在使用 gulp 构建 ZIP 文件(这是一个 NodeJS 应用程序)并假设它是预先构建在目录中的 build/myLambda.zip

基本上我想做这个。文件名是一个 terraform 变量,我希望 source_code_hash 计算必须引用该文件。

module my_lambda {
  filename = "${var.my_zip_file}"
}

模块的相关部分是:

resource "aws_lambda_function" "lambda" {
   filename            = "${var.filename}"
   source_code_hash    = "${filebase64sha256(file("${var.filename}"))}"
}

然而,当我 运行 terraform plan 时,我得到这个错误:

Error: Error in function call

  on modules\lambda\main.tf line 16, in resource "aws_lambda_function" "lambda":
  16:     source_code_hash    = "${filebase64sha256(file("${var.filename}"))}"
    |----------------
    | var.filename is "build/myLambda.zip"

Call to function "file" failed: contents of
build/myLambda.zip are not valid UTF-8;
use the filebase64 function to obtain the Base64 encoded contents or the other
file functions (e.g. filemd5, filesha256) to obtain file hashing results
instead.

filebase64sha256函数类似于base64sha256(file(...)),但是通过将两个函数结合在一起,它避免了创建文件内容的中间字符串的需要,从而避免了文件是UTF-8 编码。

因此您不需要 file 函数调用,因为读取文件是内置于该函数中的:

  source_code_hash = "${filebase64sha256(var.filename)}"