AWS Lambda uploading requires the generation of a zip archive of required source code and libraries. For use of NodeJS as the language for Lambda, it may be more typically the case that you want a source file and the node_modules directory to be included in the zip archive. The Terraform archive provider gives a file_archive resource which works well when it can be used. It can't be used when you want more than just 1 file or 1 directory. See feature request . To work around this, I came up with this code below. It executes steps but not in the required sequence. Run it once and it updates the zip file, but doesn't upload it to AWS. I run it again and it uploads to AWS.
# This resource checks the state of the node_modules directory, hoping to determine,
# most of the time, when there was a change in that directory. Output
# is a 'mark' file with that data in it. That file can be hashed to
# trigger updates to zip file creation.
resource "null_resource" "get_directory_mark" {
provisioner "local-exec" {
command = "ls -l node_modules > node_modules.mark; find node_modules -type d -ls >> node_modules.mark"
interpreter = ["bash", "-lc"]
}
triggers = {
always = "${timestamp()}" # will trigger each run - small cost.
}
}
resource "null_resource" "make_zip" {
depends_on = ["null_resource.get_directory_mark"]
provisioner "local-exec" {
command = "zip -r ${var.lambda_zip} ${var.lambda_function_name}.js node_modules"
interpreter = ["bash", "-lc"]
}
triggers = {
source_hash = "${sha1("${file("lambda_process_firewall_updates.js")}")}"
node_modules = "${sha1("${file("node_modules.mark")}")}" # see above
}
}
resource "aws_lambda_function" "lambda_process" {
depends_on = ["null_resource.make_zip"]
filename = "${var.lambda_zip}"
function_name = "${var.lambda_function_name}"
description = "process items"
role = "${aws_iam_role.lambda_process.arn}"
handler = "${var.lambda_function_name}.handler"
runtime = "nodejs8.10"
memory_size = "128"
timeout = "60"
source_code_hash = "${base64sha256(file("lambda_process.zip"))}"
}
Other related discussion includes: this question on code hashing, (see my answer) and this GitHub issue.