How do I resolve the "Unable to import module" error that I receive when I run Lambda code in Python?
Last updated: 2021-07-26
I receive the "Unable to import module" error when I try to run my AWS Lambda code in Python.
You typically receive this error when your Lambda environment can't find the specified library in the Python code. This is because Lambda isn't prepackaged with all Python libraries.
To resolve this error, create a deployment package or Lambda layer that includes the libraries that you want to use in your Python code for Lambda.
Note: The following steps show you how to create a Lambda layer rather than a deployment package. This is because you can reuse the Lambda layer across multiple Lambda functions. Each Lambda runtime adds specific /opt directory folders to the PATH variable. If the layer uses the same folder structure, your Lambda function's code can access the layer content without specifying the path.
Important: Put the library that you import for Python inside the /python folder.
It's a best practice to create a Lambda layer on the same operating system that your Lambda runtime is based on. For example, Python 3.8 is based on an Amazon Linux 2 Amazon Machine Image (AMI). However, Python 3.7 and Python 3.6 are based on the Amazon Linux AMI.
To create a Lambda layer for a Python 3.8 library:
2. Create an AWS Identity and Access Management (IAM) role with permissions to call the publish-layer-version API. Then, attach the IAM role to the EC2 instance.
Note: Your EC2 instance now has permissions to upload Lambda layers for the publish-layer-version API call.
3. Connect to your EC2 instance, and then install Python 3.8 and pip3:
$ sudo amazon-linux-extras install python3.8 $ curl -O https://bootstrap.pypa.io/get-pip.py $ python3.8 get-pip.py --user
4. Create a python folder:
$ mkdir python
5. Install the aws-xray-sdk library files into the python folder:
$ pip3 install -t python/ aws-xray-sdk
Note: Replace the aws-xray-sdk example library with the name of the Python library that you want to import.
6. Zip the contents of the python folder into a layer.zip file:
$ zip -r layer.zip python
7. Publish the Lambda layer:
$ aws lambda publish-layer-version --layer-name xray --zip-file fileb://layer.zip --compatible-runtimes python3.8 --region us-west-2