amazon-web-servicesaws-lambdaaws-lambda-layers

How to add dependency to AWS lambda layer when code is in console, not uploaded


I used pip to install locally and the dependency installed here: c:\users\info\appdata\local\programs\python\python312\lib\site-packages\my-dependency

I zipped the my-dependency folder and called it the same name my-dependency.zip

I created a new lambda layer and added it to my lambda function.

However, when I test my function, I get:

"errorMessage": "Unable to import module 'lambda_function': No module named 'my-dependency'"

I see other posts about how to include the dependency in the package I upload with my code, but my code is directly in the console and do not upload it.


Solution

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

    The issue occurs because AWS Lambda cannot locate the module from the Lambda layer you’ve created. The likely cause is the Directory structure of the zipped layer: The Python dependencies in the zip file must be in the correct directory structure (python/lib/python3.x/site-packages/) for Lambda to recognize them.

    my-dependency.zip
    └── python/
        └── lib/
            └── python3.x/
                └── site-packages/
                    └── my-dependency/
    

    Replace python3.x with the Python version used by your Lambda runtime (e.g., python3.9 for Python 3.9 runtime). To create the correct structure for you case, you can simply follow these steps, just update the python version X:

    mkdir -p python/lib/python3.x/site-packages
    cp -r c:/users/info/appdata/local/programs/python/python312/lib/site-packages/my-dependency python/lib/python3.x/site-packages/
    zip -r my-dependency.zip python/