Issue: Unable to locate module '\nStack trace:\n- /var/runtime/index.mjs when running Lambda function generated using Terraform and Node.js version 18 or higher

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement dynamic validation in Angular 4 based on specific conditions

I am looking to implement Angular 4 validation dynamically based on specific conditions within a Reactive form. Here is the scenario: There is a radio button with options: A: yes B: no If the user selects "yes", a textbox (formControlName="your_name") wil ...

Handling events in React using TypeScript

Currently diving into the world of React with Typescript and encountered a challenge involving event handling using the onClick property. I have a react component displaying a list of items from an array, and I aim to log the clicked item in the console. I ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...

Checking if an instance belongs to a specific class using a custom type guard in TypeScript

After successfully implementing the function isInstanceOfClass, which determines if an instance is of a given class, I am now faced with the task of writing the correct typing for it. class Parent { isInstanceOfClass<T>(arg: T): this is T { ...

Encountering the "Unrecognized teardown 1" error when subscribing to an Observable in Typescript and Angular2

Having trouble with using an Observable in my Angular2.rc.4 Typescript app. Check out the plunker for it here: https://embed.plnkr.co/UjcdCmN6hSkdKt27ezyI/ The issue revolves around a service that contains this code: private messageSender : Observable< ...

Exploring alternative applications of defineModel in Vue 3.4 beyond just handling inputs

The examples provided for defineModel in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to ...

The type undefined cannot be assigned to the type even with a null check

When looking at my code, I encounter an error stating Argument of type 'Definition | undefined' is not assignable to parameter of type 'Definition'. Even though I am checking if the object value is not undefined with if (defs[type] != u ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

When utilizing RxJS, the process of filtering Observable data may not function as expected if the filtering is carried out within a separate function rather than directly within the subscribe

While attempting to filter data from an external source using the RxJS filter on Observables, I encountered an issue where all records were returned instead of just the ones meeting the filtering criteria. This problem occurred when the code was within a l ...

"Discovering the root cause of Angular memory leaks and resolving them effectively is crucial for

I am facing an issue with a code that appears to be leaking, and I am seeking advice on how to identify the cause or properly unsubscribe. Even after adding an array containing all object subscriptions, the memory leakage persists. import { Component, On ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Struggling to make fetch function properly within a NextJs middleware function

I am having trouble with redirecting a user to /login if the authentication token from Laravel is invalid. I am attempting to retrieve the user and, if resp.ok() returns false, delete the invalid "token" cookie and direct the user to /login. However, I con ...

Occasionally, Lambda encounters difficulties when attempting to publish to SNS topics

My AWS Lambda is experiencing intermittent failures when attempting to publish messages to an AWS SNS topic. 2020-03-09T08:02:42.520Z Could not publish on sns with error: NetworkingError: write EPROTO 2020-03-09T08:02:42.789Z Could not publish on sns wit ...

Access an array to filter by specific key-value pairs

How can I efficiently filter an array using key and value pairs from within nested arrays? I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean value ...

Discovering the 3D coordinates of a point that is perpendicular to the midpoint of a line

(I am working with Javascript/Typescript and Three.js) Given two vectors, let's say {x:1, y:3, z:5} and {x:7, y:8, z:10}, I have a direct straight line connecting them. At the midpoint of this line, envision a disc with a radius of 1 that is perpend ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...