1

I want to update lambda layer in AWS only when there is a change the script file. For the given script file, if I need to add any more dependencies, I will add another pip install command and only then the data archive file should be updated with latest installation package and subsequently the lambda layer.

I have created a null resource which I presume should only trigger when there is a change in the script file. I have also created a data archive file which is dependant on null resource and a lambda layer which is dependant on data source.

When there is no change in the script file, terraform is still trying to run the data source sometimes and throwing this error:

error archiving directory: could not archive missing directory: ./lambda_archive/layers"

All I want is the data source to run only when there is a change in the script file.

Below is the script which does not often update frequently unless there is a new package to add.

#!/bin/bash
rm -r lambda_archive/layers
mkdir -p layers/python
cd layers/python
pip install --target . requests
pip install --target . structlog
cd -
mv layers lambda_archive/
resource "null_resource" "lambda_layer_packages" {
    provisioner "local-exec" {
        working_dir = path.module
        command     = "/bin/bash lambda-layers.sh"
    }
    
    triggers = {
        always_run = md5(file("${path.module}/lambda-layers.sh"))
    }
}
    
data "archive_file" "lambda_layer_packages_archive_file" {
    type        = "zip"
    source_dir  = "${path.module}/lambda_archive/layers"
    output_path = "${path.module}/lambda_archive/layers.zip"   
    depends_on  = [null_resource.lambda_layer_packages]
}
    
resource "aws_lambda_layer_version" "lambda_layer" {
    filename                 = "${path.module}/lambda_archive/layers.zip"
    layer_name               = "lambda_layer"
    source_code_hash         = data.archive_file.lambda_layer_packages_archive_file.output_base64sha256
    compatible_runtimes      = ["python3.9"]
    compatible_architectures = ["x86_64", "arm64"]
}
    
resource "aws_lambda_function" "some_lambda" {
    ...
    layers = [aws_lambda_layer_version.lambda_layer.arn]
    ...
}

Ideally data archive file should not be executed unless there is a change on the dependency null resource

double-beep
  • 5,031
  • 17
  • 33
  • 41
ChinnaR
  • 797
  • 3
  • 9
  • 24
  • I've left a detailed answer here: https://stackoverflow.com/questions/73671437/only-create-new-archive-file-for-lambda-when-code-changes/73676194#73676194 – Leslie Alldridge Sep 13 '22 at 20:33

0 Answers0