SAM Resource Layer - Can it Reference Another Layer?

Viewed 271

Building an AWS SAM application.

I wrote a shared layer, and then noticed I happened to reference another layer (force of habit).

Probably not best practice, but to save myself some time... anyone know if I can reference that other layer in the Serverless::LayerVersion build?

Essentially a layer within a layer (we'll call this "inception layer" haha)?

Here's my shared layer

Resources:
  sharedLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: shared
      CompatibleRuntimes:
        - python3.8
    Metadata:
      BuildMethod: python3.8

I tried:

Resources:
  sharedLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: shared
      Layers:
        - arn:aws:lambda:us-east-1:990458801000:layer:PyMySql:1
      CompatibleRuntimes:
        - python3.8
    Metadata:
      BuildMethod: python3.8

But it didn't like that.

Important Note: I do NOT want to put the PyMySql layer in my Globals as I don't want it attached to every function in my SAM app. Any layer I put in the Globals seems to get attached to every function in the SAM build.

1 Answers

So one quasi-hack I figured out is if the "shared layer" is dependent on another layer, if you load the dependent layer first in the same Serverless::Function you're calling "shared layer" then it will work.

Example:

Resources:
  sharedLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: shared
      CompatibleRuntimes:
        - python3.8
    Metadata:
      BuildMethod: python3.8

This shared layer depends on - arn:aws:lambda:us-east-1:990458801000:layer:PyMySql:1

So in your function if you call that layer first:

surfModel:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: search/surf_model
      Layers:
        - arn:aws:lambda:us-east-1:990458801000:layer:PyMySql:1
        - !Ref sharedLayer

Then !Ref sharedLayer will operate just fine (drawing on the reference to the dependent layer within the function itself).

Not the ideal solution, but it'll do for a short term fix.

Related