How to add a custom folder and file via YAML in Serverless app
Asked Answered
B

1

1

I am writing a serverless app by using SAM. I created a config folder to keep some table information and some other info. then I load it in my app.js.

when I deploy the app.js locally by using SAM deploy, I observe that the config folder will not include. would you mind advise me how to add config folder in final build folder in .aws-sam\build folder?

enter image description here

my Yaml file

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

Also when I run the project in debug mode I am getting this error:

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

I load the js file as below:

"use strict";

let response;
const AWS = require('aws-sdk');
const config = require('../config/config.js');
Barchan answered 22/10, 2019 at 10:53 Comment(3)
Any idea guys? please help.Barchan
Have you found out the fix ? If not I have a few suggestions...Prenatal
@arjithn: I am all ears...I couldn't find a solution and just moved my folder to the respective Lambda folderBarchan
C
3

To include custom files that you need to re-use in multiple functions like the config file in your case. Then you can use lambda layers.

In your template.yml you would include a layer as follow:

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

and then add it to your lambda function definition:

    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

The contents of the config/ directory will be available in the /opt/ path.

that means the full path to your config.js will be /opt/config.js and you can access it from any lambda that uses that layer.

Cinder answered 24/11, 2020 at 23:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.