Here we are going to see how to define an AWS lambda layer in the SAM template.

AWS SAM Lambda Layer:

However, this example is not completely bound to the SAM template it also works for cloud formation templates too as SAM is an extension of cloud formation.

AWS::Serverless::LayerVersion is used to create a Lambda layer version resource that can be easily integrated with any lambda function.

Typically a Lambda layer contains libraries and runtime code that is needed by the lambda function.

Syntax:

Type: AWS::Serverless::LayerVersion
Properties:
  CompatibleRuntimes: List
  ContentUri: String | LayerContent
  Description: String
  LayerName: String
  LicenseInfo: String
  RetentionPolicy: String

Among the all above properties I am interested in CompatibleRuntimes, ContentUri and RetensionPolicy because remaining all are self-explanatory.

CompatibleRuntimes defines the list of runtimes that are compatible with this Layer.

ContentUri defines the location of the libraries and runtime code, it also can be referred by an S3 object or a specific path to a local directory.

RetenctionPolicy can be either Delete or Retain it says whether the older version of the layer has to be deleted or retained.

SAM Lambda Layer Example:

A complete example of the serverless function with layers can be followed.

template.yaml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Resources: 
  PythonDepLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: !Sub "python-dep-layer"
      CompatibleRuntimes:
        - python3.8
      ContentUri: ./.build/dependencies  # (OR) S3://location
      RetentionPolicy: Delete

  ServerlessFucntion: 
    Type: AWS::Serverless::Function 
    Properties: 
       FunctionName: sample-serverless-example 
       Description: "A simple serverless example in SAM" 
       CodeUri: .serverless_example 
       Handler: src.lambda_handler
       Layers:
         - !Ref PythonDepLayer

Now before going to run sam build or sam deploywe have to make sure that the dependency folder (ContentUri) has to be existed in ./.build/dependencies.

This can be achieved in different ways based on your packaging, if you are in python runtime may be poetry taskipy or tox. Else You can use a simple shell script to build the dependencies. that completely depends on your flexibility.

If you are going with the S3 location, make sure it has a proper role to access s3 objects from this application.

Done!

References:

Happy Learning 🙂