Terraform:为什么这种尝试链接资源没有用?

时间:2019-01-10 15:49:19

标签: aws-lambda zip terraform

AWS Lambda上传需要生成所需源代码和库的zip存档。对于使用NodeJS作为Lambda的语言,更常见的情况是您希望将源文件和node_modules目录包含在zip存档中。 Terraform归档提供程序提供了一个file_archive资源,该资源可以在使用时很好地工作。如果您只需要1个文件或1个目录,则不能使用它。参见feature request。为解决此问题,我在下面提出了此代码。它执行步骤,但未按要求的顺序执行。运行它一次,它将更新zip文件,但不会将其上传到AWS。我再次运行它,并将其上传到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"))}"
}

其他相关讨论包括:this question on code hashing(请参阅我的回答)和this GitHub issue

0 个答案:

没有答案