terraform: Update a Lambda function when the code changes

AWS Lambda terraform aws_lambda_function archive_file

2 min read | by Jordi Prats

If we are using the archive_file datasource to zip some Lambda function to be able to push it to AWS, we need to se the source_code_hash with it's hash to make sure the function gets updated when it changes:

If we try to use the filebase64sha256 function like this:

data "archive_file" "demo_lambda_zip" {
  type        = "zip"
  source_dir  = "${path.module}/src/demo_lambda"
  output_path = "${path.module}/zip/demo_lambda.zip"
}

resource "aws_lambda_function" "demo_lambda" {
  filename         = data.archive_file.demo_lambda_zip.output_path
  source_code_hash = filebase64sha256(data.archive_file.demo_lambda_zip.output_path)
  role             = aws_iam_role.demo_lambda.arn
  function_name    = "demo_lambda"
  handler          = "handler.lambda_handler"
  runtime          = "python3.8"
}

For the first run, when the actual zip file is not yet created, it will fail with the following message:

$ terraform plan
(...)
Error: Error in function call
│ 
│   on main.tf line 94, in module "lambda_function":
│  94:   source_code_hash = filebase64sha256(data.archive_file.demo_lambda_zip.output_path)
│     ├────────────────
│     │ data.archive_file.lambda_function.output_path is "./zip/demo_lambda.zip"
│ 
│ Call to function "filebase64sha256" failed: open files/demo_lambda.zip: no such file or directory.
╵

To avoid this kind of situations, the archive_file datasource already provides it's hash as one of it's outputs: output_base64sha256: We just need to update the aws_lambda_function to use it as follows:

data "archive_file" "demo_lambda_zip" {
  type        = "zip"
  source_dir  = "${path.module}/src/demo_lambda"
  output_path = "${path.module}/zip/demo_lambda.zip"
}

resource "aws_lambda_function" "demo_lambda" {
  filename         = data.archive_file.demo_lambda_zip.output_path
  source_code_hash = data.archive_file.demo_lambda_zip.output_base64sha256
  role             = aws_iam_role.demo_lambda.arn
  function_name    = "demo_lambda"
  handler          = "handler.lambda_handler"
  runtime          = "python3.8"
}

Posted on 01/04/2022

Categories