Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include static files on Serverless Framework?

I'm creating a NodeJS service with serverless framework to validate a feed so I added a schema file (.json) to the service but I can’t make it work. It seems to not be included in the package. Lambda doesn't find that file.

First I just run sls package and check the zip contents but the file is not present. I also tried to include the file with:

package:
  include:
    - libs/schemas/schema.json

but still not works.

How can I make sure a static file is included in the package and can be read inside the lambda function?

like image 725
yabune Avatar asked Feb 01 '18 12:02

yabune


People also ask

How do I set environment variables for serverless?

To reference environment variables, use the ${env:SOME_VAR} syntax in your serverless. yml configuration file. It is valid to use the empty string in place of SOME_VAR .

What is Handler in serverless?

The Lambda function handler is the method in your function code that processes events. When your function is invoked, Lambda runs the handler method. When the handler exits or returns a response, it becomes available to handle another event.


2 Answers

It depends on how you are actually trying to load the file.

Are you loading it with fs.readFile or fs.readFileSync? In that case, Serverless doesn't know that you're going to need it. If you add a hint for Serverless to include that file in the bundle then make sure that you know where it is relative to your current working directory or your __dirname.

Are you loading it with require()? (Do you know that you can use require() to load JSON files?) In that case, Serverless should know that you need it, but you still need to make sure that you got the path right.

If all else fails then you can always use a dirty hack. For example if you have a file 'x.json' that contains:

{
  "a": 1,
  "b": 2
}

then you can change it to an x.js file that contains:

module.exports = {
  "a": 1,
  "b": 2
};

that you can load just like any other .js file, but it's a hack.

like image 136
rsp Avatar answered Sep 29 '22 11:09

rsp


From what I've found you can do this in many ways:

  • As it is stated in another answer: if you are using webpack you need to use a webpack plugin to include files in the lambda zip file

  • If you are not using webpack, you can use serverless package commnad (include/exclude).

  • You can create a layer and reference it from the lambda (the file will be in /opt/<layer_name>. Take in consideration that as today (Nov20) I haven't found a way of doing this if you are using serverless.ts without publishing the layer first (lambda's layer property is an ARN string and requires the layer version).

  • If your worried about security you can use AWS Secrets as it is stated in this answer.

  • You can do what @rsp says and include it in your code.

like image 44
lmiguelmh Avatar answered Sep 29 '22 11:09

lmiguelmh