Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deploying lambdas effectively (only deploy those that changed) with Terraform/CloudFormation/Something else

So far, I have been using CloudFormation to deploy my lambdas. I find this process very slow and inefficient tho - eg. it may take minutes but it should have taken just seconds if its just deploying that 1 function? Most functions would not have changed but I believe CloudFormation does not differentiate and will deploy everything anyway. Is there a way I can do it more effectively? Like check what has changed and only deploy the changes?

Another benefit is I can have less versions perhaps?

like image 593
Jiew Meng Avatar asked Dec 13 '18 06:12

Jiew Meng


People also ask

What tool do you utilize to build and deploy your Lambda?

Terraform. There are a few ways to deploy Lambda using terraform. We can use basic AWS provider resource modules and build the code ourselves using the CICD pipeline or the AWS supported module. The module was created with multiple AWS resources to simplify the Lambda build and deployment process.


2 Answers

You can use the source_code_hash of the aws_lambda_function resource to have Terraform check if the Lambda function has changed. If nothing has changed then it won't upload a new version and your plan will show no changes to be made.

This is given as an example in the docs:

resource "aws_lambda_function" "test_lambda" {
  filename         = "lambda_function_payload.zip"
  function_name    = "lambda_function_name"
  role             = "${aws_iam_role.iam_for_lambda.arn}"
  handler          = "exports.test"
  source_code_hash = "${base64sha256(file("lambda_function_payload.zip"))}"
  runtime          = "nodejs8.10"

  environment {
    variables = {
      foo = "bar"
    }
  }
}
like image 74
ydaetskcoR Avatar answered Oct 23 '22 10:10

ydaetskcoR


I created this Terraform module to address exactly this issue. Even setting the source_code_hash isn't sufficient because when zips are made they typically include some filesystem metadata. With my module the hash should be stable (only change when the source changes). The module is specific to Python, but the hash stability could be applied to any runtime.

like image 24
Robert Jordan Avatar answered Oct 23 '22 09:10

Robert Jordan