Error: “ModuleNotFoundError” when I set up a lambda function importing the python package called “paramiko”

Actually “ModuleNotFoundError” and “Module cannot be loaded” are common errors for Lambda functions in Python. These errors are usually due to incorrect folder structure or file permissions with the deployment package .zip file.

The detailed solution is as below.

I use Python 3.6 and launch an EC2 instanc using Amazon Linux (AMI – amzn-ami-hvm-2018.03.0.20181129-x86_64-gp2).  Then I executed follow commands to initiate virtual environment and install Paramiko package.

  1. SSH to the instance
  2. sudo yum update
  3. sudo yum install python36 -y
  4. python3 -m venv ./venv
  5. cd venv
  6. source ./bin/activate
  7. pip install –target ./package paramiko

Secondly, I create sample code and zip with Paramiko package.

  1. cd package
  2. zip -r ../function.zip .   (Create a ZIP archive with the contents of the library)
  3. cd ..
  4. create the lambda_function.py, sample code is as below.
import json
import _cffi_backend

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
  1. zip -g function.zip lambda_function.py  (Add function code to the archive)

Next I transfer function.zip to my local and then create new lambda function by uploading it.

  1. Copy function.zip to local  (you can use WinSCP or SCP to transfer file)
  2. Login to Lambda console to create new lambda function – python 3.6
  3. In the Function code section, expand the Code entry type drop-down list, and then choose Upload a .ZIP file.
  4. Save it and test it.

Finally you will see the Execution Result: succeeded.

1 Comment

  • https://uchinoshitsuji.com February 20, 2021

    Best view i have ever seen !

Leave a Reply