1

我正在使用 SAM 编写无服务器应用程序。我创建了一个配置文件夹来保存一些表信息和一些其他信息。然后我将它加载到我的 app.js 中。

当我使用 SAM deploy 在本地部署 app.js 时,我观察到配置文件夹将不包括在内。你介意告诉我如何在 .aws-sam\build 文件夹的最终构建文件夹中添加配置文件夹吗?

在此处输入图像描述

我的 Yaml 文件

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for test

Globals:
  Function:
    Timeout: 120

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs10.x
      Events:
        HelloWorld:
          Type: Api 
          Properties:
            Path: /hello
            Method: get

此外,当我在调试模式下运行项目时,我收到此错误:

{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module '../config/config.js'"
}

我加载js文件如下:

"use strict";

let response;
const AWS = require('aws-sdk');
const config = require('../config/config.js');
4

1 回答 1

2

要包含您需要在多个功能中重复使用的自定义文件,例如您的案例中的配置文件。然后你可以使用 lambda 层。

在您的 template.yml 中,您将包含如下图层:

  ConfigLayer:
    Type: "AWS::Serverless::LayerVersion"
    Properties:
      CompatibleRuntimes:
        - nodejs10.x
      ContentUri: ./config/

然后将其添加到您的 lambda 函数定义中:

    Type: AWS::Serverless::Function
    Properties:
      Handler: cmd/lambdas/hello-world/app.lambdaHandler
      CodeUri: src/
      Runtime: nodejs10.x
      Layers:
        - Ref: ConfigLayer
      Events:
        CatchAll:
          Type: Api
          Properties:
            Path: /hello-world
            Method: GET

目录的内容将在路径config/中可用。/opt/

这意味着您的遗嘱的完整路径,config.js/opt/config.js可以从使用该层的任何 lambda 访问它。

于 2020-11-24T23:06:06.030 回答