Serverless: Use Custom Layer in AWS Lambda

After deploy our custom layer in AWS Lambda, we can to use that layer in our AWS Lambda functions. How to do that?

Here's my step by step example reusing AWS Lambda layer when develop AWS Lambda functions using Serverless Framework:

1. Get the ARN Info of the Layer

The Layer ARN Info will be in this format
arn:aws:lambda:aws-region:random-number:layer:audiowaveform:1

2. Add Layer (ARN Info) in your serverless.yml
Create a new serverless project, you can check my previous post for it.  Open serverless.yml, add layers info inside the functions, here's the example.

You can add multiple layers for each AWS Lambda functions. 

3. Test Custom Layer


Every binary added to AWS Lambda will be added to /opt path. So in my case, the audiowaveform binary path will be /opt/audiowaveform

You can see the example in my handler.js. It will try to find the version of /opt/audiowaveform binary in our custom layer.

Don't forget to run sls deploy after make a changes.

'use strict';

const { execSync } = require('child_process');

module.exports.hello = async (event) => {

  const audioWaveVersion = execSync('/opt/audiowaveform -v').toString();
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        audioWaveVersion: audioWaveVersion
      }
    ),
  };
};
We can see that our audiowaveform binary executed normally. 



That's all!

Comments