oxer
oxer

Reputation: 1145

Permission denied after uploading AWS Lambda python zip from S3

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)?

Upvotes: 6

Views: 11934

Answers (4)

Han
Han

Reputation: 426

Within the directory where your lambda_function.py is located, run the following commands:

chmod 644 $(find . -type f)
chmod 755 $(find . -type d)

The above commands make all files and folders in the current directory readable by any user.

Upvotes: 1

Ralph Willgoss
Ralph Willgoss

Reputation: 12163

I had a similar issue deploying a Lambda via Azure Devops.
The following python task fixed it:

- task: PythonScript@0
        displayName: zip inspector.py
        inputs:
          scriptSource: inline
            script: |
              from zipfile import ZipFile
              with ZipFile('inspector.zip', 'w') as zf:
                zf.write('inspector.py')

Upvotes: 0

Tyrion
Tyrion

Reputation: 485

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.

Upvotes: 1

oxer
oxer

Reputation: 1145

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).

Upvotes: 9

Related Questions