如何触发terraform上传新的lambda代码

时间:2018-02-02 07:28:02

标签: amazon-web-services aws-lambda terraform

我使用Terraform部署lambda如下,但有以下问题:

1)我希望始终调用null_resource.lambda或更改stop_ec2.py以使stop_ec2_upload.zip不会过时。我应该在触发器{}中写什么?

2)当stop_ec2_upload.zip发生变化时,如何让aws_lambda_function.stop_ec2将新的stop_ec2_upload.zip更新为云?

现在我必须销毁aws_lambda_function.stop_ec2然后再创建它。我可以在代码中编写任何内容,这样当我运行terraform apply时,1)和2)会自动发生吗?

resource "null_resource" "lambda" {
  triggers {
   #what should I write here?
  }

  provisioner "local-exec" {
    command = "mkdir -p lambda_func && cd lambda_py && zip     
../lambda_func/stop_ec2_upload.zip stop_ec2.py && cd .."
  }
}
resource "aws_lambda_function" "stop_ec2" {
    depends_on = ["null_resource.lambda"]
    function_name = "stopEC2"
    handler = "stop_ec2.handler"
    runtime = "python3.6"
    filename = "lambda_func/stop_ec2_upload.zip"
    source_code_hash =     
"${base64sha256(file("lambda_func/stop_ec2_upload.zip"))}"
    role = "..."
}

2 个答案:

答案 0 :(得分:5)

我阅读了Chandan提供的链接并想通了。 这是我的代码,它完美无缺。

实际上,使用“archive_file”和source_code_hash,我不需要触发器。每当我创建一个新文件stop_ec2.py或修改它。当我运行terraform时,文件将被重新压缩并上传到云端。

data "archive_file" "stop_ec2" {
  type        = "zip"
  source_file = "src_dir/stop_ec2.py"
  output_path = "dest_dir/stop_ec2_upload.zip"
}

resource "aws_lambda_function" "stop_ec2" {
  function_name    = "stopEC2"
  handler          = "stop_ec2.handler"
  runtime          = "python3.6"
  filename         = "dest_dir/stop_ec2_upload.zip"
  source_code_hash =     
"${data.archive_file.stop_ec2.output_base64sha256}"
  role             = "..."
}

答案 1 :(得分:1)

这些可能会有所帮助:

triggers {
    main         = "${base64sha256(file("source/main.py"))}"
    requirements = "${base64sha256(file("source/requirements.txt"))}"
  }

triggers = {
    source_file = "${sha1Folder("${path.module}/source")}"
  }

参考:https://github.com/hashicorp/terraform/issues/8344