An Nguyen
An Nguyen

Reputation: 117

Can't write to writable folder /tmp/ on S3 bucket

I've tried writing a file to writable /tmp/ folder inside my bucket with a lamda function but got AccessDenied error. This is weird since I can do it by calling the lambda function locally. Below is the code for the lambda function:

import json
import boto3
import os

def lambda_handler(event, context):
    # TODO implement
    print(event)
    session = boto3.Session(profile_name=os.environ.get("MY_PROFILE", None))
    
    client = session.client("s3")
    os.chdir('/tmp')
    with open('test.txt', "w") as f:
        f.write("testing")
    client.upload_file('test.txt', 'my-bucket', 'tmp/test.txt')

and here is the error log:

{
  "errorMessage": "Failed to upload test.txt to my-bucket/tmp/test.txt: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied",
  "errorType": "S3UploadFailedError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 14, in lambda_handler\n    client.upload_file('test.txt', 'gp-model-bucket', 'tmp/test.txt')\n",
    "  File \"/var/runtime/boto3/s3/inject.py\", line 131, in upload_file\n    extra_args=ExtraArgs, callback=Callback)\n",
    "  File \"/var/runtime/boto3/s3/transfer.py\", line 287, in upload_file\n    filename, '/'.join([bucket, key]), e))\n"
  ]
}

Can someone help me out please?

Upvotes: 1

Views: 999

Answers (1)

Marcin
Marcin

Reputation: 238279

You should add S3 write permissions into your AWS Lambda execution role. You can add the following IAM policy to your role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::my-bucket/*"
        }
    ]
}

Other permissions may be required, e.g. KMS permissions if your bucket uses default KMS encryption.

Upvotes: 2

Related Questions