Permission denied after uploading AWS Lambda python zip from S3

我的梦境 提交于 2020-01-04 03:15:09

问题


When uploading a python zip package to AWS Lambda from S3 I get the following cryptic error:

module initialization error: [Errno 13] Permission denied: '/var/task/lambda_function.py'

The error seems to be that if you create a zip package with restrictive permissions, then AWS gets confused. Essentially, AWS unzips your package with the permissions you gave it and tries to use it. What can make this especially confusing is that you may be able to see part of the zip files from the AWS Lambda inline code editor (so you clearly have some permission), but the Lambda function will give the above error.

What is the best way to handle this (either a better error message or resolve the problem)?


回答1:


The approach I used was to be careful in how I created my zip package in python.

Instead of doing something like

ziph = zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED)
ziph.writestr(file_name, my_data)

I replaced the last line above with

zinfo = zipfile.ZipInfo(file_name)
zinfo.external_attr = 0o777 << 16  # give full access to included file
ziph.writestr(zinfo, my_data)

To make sure to explicitly grant full permissions. If you don't do this, then writestr will use too restrictive default permissions. (Note: the above is for python 3.6).




回答2:


I deployed my Python2.7 code to AWS using serverless and had a similar problem that was logged in CloudWatch as:

Unable to import module handler: No module named handler

I searched solution online and got the information that, when serverless deploys the code to AWS (to date), it probably deploys the file with the same permission as it is on the filesystem.

In this case, as my Python file handler.py is read-only, Lambda will not be able to execute the file. Therefore, the way I solve the problem is to set 644 permission before deployment. In the command line, run:

chmod 644 handler.py

Hope it helps. By the way, I am using macOS Mojave.



来源:https://stackoverflow.com/questions/46076543/permission-denied-after-uploading-aws-lambda-python-zip-from-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!