Unable to use lambda layer in lambda function (using aws cdk )

0

I am using aws cdk with typescript to develop, and I want to use axios in my lambda function

I encoutered error

{ "errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module 'opt/nodejs/axios'\nRequire stack:\n- /var/task/dbcall.js\n- /var/runtime/index.mjs", "trace": [ "Runtime.ImportModuleError: Error: Cannot find module 'opt/nodejs/axios'", "Require stack:", "- /var/task/dbcall.js", "- /var/runtime/index.mjs", " at _loadUserApp (file:///var/runtime/index.mjs:1061:17)", " at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)", " at async start (file:///var/runtime/index.mjs:1256:23)", " at async file:///var/runtime/index.mjs:1262:1" ] }

This is my stack code

export class CddStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);


    const axiosLayer = new LayerVersion(this, 'axiosLayer', {
      compatibleRuntimes: [
        Runtime.NODEJS_16_X,
      ],
      code: Code.fromAsset('./resources/layers/axios'),
      description: "axios",

    })

    //define an aws lambda resource 
    const dbcall = new lambda.Function(this, 'dbCall', {
      runtime: lambda.Runtime.NODEJS_16_X,
      code: lambda.Code.fromAsset('lambda'),
      handler: 'dbcall.handler',
      timeout: Duration.seconds(300),

      layers: [axiosLayer],
    })
    const rule = new events.Rule(this, 'Schedule Rule', {
      schedule: events.Schedule.cron({ minute: '10', hour: '0' })
    })
    rule.addTarget(new targets.LambdaFunction(dbcall))
  }
}

This is my folder structure Enter image description here

my lambda function code

const { axios } = require('opt/nodejs/axios');

const { hash, getKey } = require('./hash')
exports.handler = async function (event) {
....
}

The code inside axios.ts

// @ts-nocheck
export { axios } from 'axios'

my tsconfig.json set up

"paths": { "opt/nodejs/axios": ["resources/layers/axios/nodejs/axios.ts"] },

RECJ
질문됨 7달 전536회 조회
1개 답변
1
수락된 답변

The error you're encountering suggests that AWS Lambda is unable to find the axios module, and it's looking for it in a directory that does not exist, such as 'opt/nodejs/axios'. This issue might be related to how you've bundled and deployed your Lambda function.

To resolve this issue, you can follow these steps:

  1. Check Dependencies: Ensure that axios is properly added to your Lambda function's deployment package. In your AWS CDK project, make sure that axios is listed as a dependency in your package.json file.

  2. Bundling: When you deploy a Lambda function with dependencies, it's essential to bundle the function with its dependencies. You can use tools like AWS SAM, Serverless Framework, or AWS CDK to help with bundling. Make sure your bundling process includes the node_modules directory.

  3. Build Lambda Function: Before deploying, ensure that you build your Lambda function with the bundled dependencies and package it correctly.

Shubham
답변함 7달 전
profile pictureAWS
전문가
검토됨 7달 전
  • I found out if I remove the node_modules folder from git_ignore file, everything will work..., but it is a big folder, Can I really ignore it ?

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠