25

I deploy lambda using Terraform as follows but have following questions:

1) I want null_resource.lambda to be called always or when stop_ec2.py is changed so that stop_ec2_upload.zip is not out-of-date. What should I write in triggers{}?

2) how to make aws_lambda_function.stop_ec2 update the new stop_ec2_upload.zip to cloud when stop_ec2_upload.zip is changed?

right now I have to destroy aws_lambda_function.stop_ec2 then create it again. is there anything I can write in the code so that when I run terraform apply, 1) and 2) will happen automatically?

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 Answers 2

38

I read the link provided by Chandan and figured out. Here is my code and it works perfectly.

In fact, with "archive_file", and source_code_hash, I do not need trigger. whenever I create a new file stop_ec2.py or modify it. when I run terraform, the file will be re-zipped and uploaded to cloud.

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             = "..."
}
Sign up to request clarification or add additional context in comments.

1 Comment

use source_dir to replace source_file if you wish to pack to whole directory
4

These might help:

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

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

REF: https://github.com/hashicorp/terraform/issues/8344

2 Comments

Thanks Chandan, I will try and let you know.
Hi CHandan, I read your link and figure out the answer. see my post below. I do not know how your code works. e.g. I do not know what sha1Folder and requirements.txt are. But archive_file introduced in the link you provided works well. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.