My Terraform setup involves a Lambda function with a Node.js version of >= 18, following the steps outlined in this helpful article. However, upon attempting to invoke the Lambda function, CloudWatch throws the following error:
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'slack-notification'\nRequire stack:\n- /var/runtime/index.mjs",
I'm puzzled by this error. Can someone shed light on why the "Error: Cannot find module 'slack-notification'" occurs when triggering the Lambda function?
Terraform Infrastructure:
resource "null_resource" "lambda_dependencies" {
triggers = {
updated_at = timestamp()
}
provisioner "local-exec" {
command = <<EOF
npm install
EOF
working_dir = "${path.module}${var.lambda_relative_path}"
}
}
data "archive_file" "lambda-zip" {
type = "zip"
source_dir = var.lambda_path
output_path = "lambda_function.zip"
depends_on = [null_resource.lambda_dependencies]
}
resource "aws_lambda_function" "lambda_module" {
filename = data.archive_file.lambda-zip.output_path
function_name = "gitlab-slack-integration-${var.environment}"
role = aws_iam_role.iam_for_lambda.arn
handler = "slack-notification.handler"
source_code_hash = data.archive_file.lambda-zip.output_base64sha256
runtime = "nodejs18.x"
environment {
variables = {
env = var.environment
}
}
}
slack-notification.ts file:
import { SNSEvent, Context } from "aws-lambda";
export const handler = async (event: SNSEvent, context: Context) => {
const snsMessage = JSON.parse(event.Records[0].Sns.Message);
console.log({ snsMessage });
return context.logStreamName;
};
Directory structure:
├── src
│ ├── functions
│ │ └── slack-notification.ts
│ ├── package-lock.json
│ ├── package.json
│ └── tsconfig.json
└── terra-infra
├── backend-dev.tf
├── dev
│ └── functions
│ ├── api-gateway.tf
│ ├── backend.tf
│ ├── lambda.tf
│ ├── lambda_function.zip
│ ├── provider.tf
│ ├── sns-topic.tf
│ ├── variables.auto.tfvars
│ └── variables.tf
├── module
├── remote-state
│ ├── main.tf
│ ├── provider.tf
│ ├── terraform.tfstate.backup
│ ├── variables.auto.tfvars
│ └── variables.tf
└── run-env.sh