Zip AWS Lambda function on the fly

terraform

Terraform has been a great tool for me to maintain infrastructure as a code (IaC). In fact, 90% of our current environment infrastructure is provisioned via Terraform.

Lately, I’ve stumbled upon a challenging case: How to zip AWS Lambda function on the fly without using external script?

Well, apparently there’s a little trick that doe’s this job:archive_file data source:

data "archive_file" "lambda_zip" {
    type        = "zip"
    source_dir  = "source"
    output_path = "lambda.zip"
}

resource "aws_lambda_function" "func" {
  filename = "lambda.zip"
  source_code_hash = "${data.archive_file.lambda_zip.output_base64sha256}"
  function_name = "my_lambda"
  role = "${aws_iam_role.lambda.arn}"
  description = "Function desc"
  handler = "index.handler"
  runtime = "nodejs4.3"
}

Voila! Works like a charm.

Having said that, please consider the following:

  1. Essentially, this is deploying code, and most of the time, you wouldn’t want to do that via a configuration management system like terraform.
  2. The local-exec provisioner is still useful if your code has 3rd party dependencies (e.g.npm-installlpip-install install).

That’s all for today folks!

Leave a Reply