AWS Amplify and importing Lambda Layers in Python gives module not found error

Viewed 1391

How does one import the assets of a shared lambda layer? Following this, I have created the lambda layer, added shared code to the layer. added the layer to a function. now in the lambda function that is using the layer, how do you use the files dropped in the opt folder of the layer created? The documentation says you can look for files in the opt path of the lambda layer. But what if there are multiple lambda layers? How do you narrow the opt path down to the specific layer?

EDIT

My new folder structure as below. I am trying to call the common shared utility class called my_utils in the file myClass.py from Index.py and have dropped the layer function file in both site-packages folder as well as the opt folder

app-root
  -amplify
     -backend
        -function
          -myLayer
            -lib\python\lib\python3.8\site-packages\myClass.py
            -opt\myClass.py
  -amplify
     -backend
        -function
          -myFunction
            -Index.py

Below are the various combinations I tried for importing in my calling handler Index.py

from myClass import my_utils
import myClass
import my_utils

With the above arrangements and import statements, I am still getting a ModuleNotFoundError

1 Answers

From the documentation about lambda layers.

"Layers are applied in the order that's specified, merging any folders with the same name."

https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

Importing python layers shown here: https://adhorn.medium.com/getting-started-with-aws-lambda-layers-for-python-6e10b1f9a5d

layer 1

def foo():
  print('I am from layer 1')
  return 1

layer 2

def bar():
  print('I am from layer 2')
  return 1

Then just import the function from the layers like so. It doesn't matter where they are.

actual function

import foo
import bar

In order for the imports to work correctly, make sure you put your layers in an opt/python directory and zip up the contents. I got this information from: https://stackoverflow.com/a/54796202/5647552

Note: The order of the different layers is not important unless you have layers with the same function name in them. Like if two layers were exporting the same function: foo(), then the order will dictate which one you import in your actual function.

Related