DEV Community

Gordon_Gao
Gordon_Gao

Posted on • Edited on

How I setup layer on serverless.yml

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: ap-southeast-2
  iamRoleStatements:
    - Effect: 'Allow'
      Action:
        - 'lambda:InvokeFunction'
        - 'lambda:InvokeAsync'
      Resource: '*'
environment:
  variable1: value1
layers:
  axios:
    path: deps
    name: axios
    description: axios module
package:
  exclude:
    - .prettierrc
    - .eslintrc
    - ./node_modules/**
    - ./package.json
    - ./package-lock.json

functions:
  hello:
    handler: handler.hello
    layers:
      - Ref: AxiosLambdaLayer

Upload layers

layers:
  axios:
    path: deps
    name: axios
    description: axios module

In the Layers property, you should point out which folder in the project directory you are going to upload to AWS Lambda as layers.

The key point I am going to illustrate here is,

do not use nodejsas folder's name (I use deps here) and there must be a folder which is named with nodejs in this folder (deps).

As the Serverless Framework will zip the folder automatically when you run serverless deploy and upload the zip file to AWS, when the lambda handler.js require module, lambda will navigate it to /opt/nodejs/ to find out the module.

In the nodejs folder, there is package.json file, and run npm install --save for download all modules locally. Then there are package.json, package-lock.json and node_modules under nodejs.

Ref the layer

functions:
  hello:
    handler: handler.hello
    layers:
      - Ref: AxiosLambdaLayer

In the field of function, the function which need layers created above should config with layers property. use Ref and the value should be layer name with capitalized initial letter plug string of LambdaLayer(eg.AxiosLambdaLayer).

If you are going to use existed layer, you can use ARN

excluded files

package:
  exclude:
    - .prettierrc
    - .eslintrc
    - ./node_modules/**
    - ./package.json
    - ./package-lock.json

Using ./ for just excluding node_modules and package.json from root directory, do not use node_modules/** and package.json, it will exclude node_modules and package.json from deps/nodejs/ folder.

useful link

Top comments (0)