Creating AWS Lambda layers

Creating AWS Lambda layers

How Lambda layer files should be structured and how to reference them.

I was asked to help create AWS Lambda layers because a customer wasn't sure how the folder structure works.

For example, this is a helper file named helpers.js.

'use strict';

const log = async (func, msg) => {
  console.log(func, msg);
};

const is_valid_format_email = (email) => {
  const regex = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@\w+([\.-]?\w+)*(\.\w{2,40})+$/i;
  return regex.test(email);
};

const is_valid_domain_email = (domain, email) => {
  const parts = email.split('@');
  if (parts.length == 2) {
    if (parts[1] == domain) {
      const regex = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")$/i;
      return regex.test(parts[0]);
    } else {
      return false;
    }
  } else {
    return false;
  }
};

const is_valid_password = (password) => {
  const regex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$&*])(?=.*[0-9]).{12,64}$/;
  return regex.test(password);
};

exports.log = log;
exports.is_valid_format_email = is_valid_format_email;
exports.is_valid_domain_email = is_valid_domain_email;
exports.is_valid_password = is_valid_password;

The folder structure should be like this:

  • Top-folder

    • nodejs

      • node_modules

        • constants.js

        • helpers.js

If using AWS Console, just zip up the nodejs folder. You'll have a new file like this:

  • Folder

    • nodejs.zip

    • nodejs

      • node_modules

        • constants.js

        • helpers.js

Then, just upload nodejs.zip to the layer. In the Lambda function, add the layer to the function and include the files as below:

'use strict';
const constants = require('constants.js');
const helpers = require('helpers.js');