使用 AWS re:Post 即表示您同意 AWS re:Post 使用條款

How to create lambda function with nodejs from cloudformation inline?

0

I am new to lambda and node-js and want to create a CF template to create a lambda function inline without passing the lambda code from a S3 bucket zip file.

When I tried below code, it fails with error `Cannot find module 'app' as the CFT didn't deploy it as a node package and app.js and the nodejs directory structure is missing in it. Is there a way to create such lambda function without manually creating the zip file and adding it to the cloudFormation template? I can easily do it in python, but not sure if it's a limitation for lambda with nodejs cloudformation.

My CloudFormation Template:

Resources:
  OnConnectFunction:
    Type: "AWS::Lambda::Function"
    Properties:
      Description: OnConnectFunction
      Handler: app.handler
      MemorySize: 256
      Runtime: nodejs12.x
      Role: !GetAtt 'LambdaIAMRole.Arn'
      Timeout: 60
      Environment:
        Variables:
          TABLE_NAME:
            Ref: TableName
      Code:
        ZipFile: |
          const AWS = require('aws-sdk');
          const ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10', region: process.env.AWS_REGION });
          exports.handler = async event => {
            const putParams = {
              TableName: process.env.TABLE_NAME,
              Item: {
                connectionId: event.requestContext.connectionId
              }
            };

            try {
              await ddb.put(putParams).promise();
            } catch (err) {
              return { statusCode: 500, body: 'Failed to connect: ' + JSON.stringify(err) };
            }

            return { statusCode: 200, body: 'Connected.' };
          };

Error when the lambda is invoked:

{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'app'\nRequire stack:\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module 'app'",
        "Require stack:",
        "- /var/runtime/UserFunction.js",
        "- /var/runtime/index.js",
    ]
}
AWS
已提問 3 年前檢視次數 5303 次
1 個回答
2
已接受的答案

Your Handler attribute should be: index.handler. See here

profile pictureAWS
專家
已回答 3 年前
profile picture
專家
已審閱 6 個月前
profile picture
專家
已審閱 1 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南