I was experiencing issue with running lambda function with uploaded .zip
file of Python script, which always produces "Unable to import module '...': No module named ..."
(I have made sure my lambda handler matched my Python file name), and through online research, I have found that the way files are zipped is very strict in this case.
The solution provided following command examples
Wrong command:
$ ls
lambda_sample
$ zip -r lambda_sample lambda_sample
Correct command:
$ cd lambda_sample
$ zip -r ../lambda_sample .
And indeed, the second command worked for me.
So I wonder why won't the first command work? Also, I'm using macOS, and by right clicking folder and Compress [folder_name]
would produce a [folder_name].zip
file not readable by Lambda, hence produce the same error I mentioned in the beginning. Could anyone provide any insight?
AWS Lambda expects your handler in the base/root of the zip file, and the zip
commands you show generate different file layouts.
I'll demonstrate with some examples from my own system.
This is an example of your first command:
> ls
package
> zip -r package package
adding: package/ (stored 0%)
adding: package/lambda.py (deflated 38%)
adding: package/process/ (stored 0%)
adding: package/process/__init__.py (stored 0%)
adding: package/process/aws.py (deflated 56%)
# ... etc.
If I unzip package.zip
, the folder structure of the resultant unzipped file looks like this:
package/lambda.py
package/process/
package/process/__init__.py
# and so on
Now, an example of your second command, where I cd package
first:
> zip -r ../package .
adding: lambda.py (deflated 38%)
adding: process/ (stored 0%)
# ... etc.
So the resulting unzipped file if I unzip package.zip
looks like this:
lambda.py
process/
process/__init__.py
# etc.
So in the second case, you don't have the parent directory after expanding the ZIP, and AWS Lambda will work correctly.