Home > other >  Why do I get unable to import module when creating a custom AWS Lambda Layer for Python?
Why do I get unable to import module when creating a custom AWS Lambda Layer for Python?

Time:12-13

I have a module called custom_module.py which has functions and methods that I would like to use across a few different Lambdas. The code looks like this:

def test():
    return 'Custom module'

I tried to convert this into a Lambda Layer by zipping up this file and using the form to create a layer. Everything seemed to work nicely, and I imported the module into my Lambda for use, like so:

import json
from custom_module import test

print('Loading function')

def lambda_handler(event, context):
    return test()

Unfortunately, running this returns a "Unable to import module 'lambda_function': No module named 'custom_module'" error. What exactly am I doing wrong here? I have the correct runtimes and architecture specified as well.

Edit

Going by the comment, I tried this file structure:

layer
|
 --- python
     |
      --- custom_module
          |
           --- __init__.py (contains the test() method)

I zipped up the layer folder as layer.zip and uploaded it. Still get the same issue unfortunately.

CodePudding user response:

As per the docs, for Python runtimes, the Lambda layer should only have 1 subfolder called python so that the Lambda can access the layer content without the need to specify the path (or it needs to be a site package within python/lib/python3.9/site-packages).

You have 2 subfolders - layer and then python.

Change your file structure to have your custom_module inside the python folder only.

layer.zip
|
 --- python
     |
      --- custom_module
          |
           --- __init__.py (contains the test() method)
  • Related