How could I use aws lambda to write file to s3 python?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Writing a file to S3 from AWS Lambda with Python is a common serverless pattern for reports, transformed payloads, exports, and event archives. The mechanics are simple with boto3, but a good implementation also needs correct IAM permissions, stable bucket configuration, and clear error handling.
In practice, there are two common approaches: upload bytes directly with put_object, or write a temporary file under /tmp and upload that file. The first is simpler for small outputs. The second is useful when a library expects a real file.
Upload Small Content Directly
If you already have the content in memory, put_object is the simplest solution:
This is the normal answer for text files, JSON payloads, and other modest outputs that fit comfortably in memory.
Use Environment Variables for Bucket and Prefix
Hardcoding bucket names makes promotion between environments awkward. A better pattern is to read configuration from environment variables:
That keeps the function reusable across dev, staging, and production.
Use /tmp When You Need a Real File
If a library generates output on disk, write to Lambda's temporary storage and upload the file:
This is useful for generated CSVs, PDFs, ZIP files, or other file-oriented workflows.
IAM Permissions Are Required
The Lambda execution role must be allowed to write to the target bucket and key prefix:
Without that permission, the code is correct but the upload will still fail. If the bucket uses encryption or stricter policies, additional permissions may also be needed.
Add Error Handling and Logging
S3 writes should log enough context to debug failures:
That is much more useful in CloudWatch than a generic failure message with no bucket or key information.
Common Pitfalls
The biggest mistake is forgetting S3 write permission on the Lambda execution role. The function then fails even though the Python code is correct.
Another common issue is hardcoding the bucket name and key prefix, which makes deployment across environments fragile.
Developers also sometimes write large files to /tmp without considering Lambda storage limits or cleanup. Temporary storage is useful, but it is not infinite.
Finally, do not return success before the S3 call has actually completed. Wrap the upload path in proper exception handling so failures propagate clearly.
Summary
- Use
boto3withput_objectfor direct in-memory uploads from Lambda. - Use
/tmpplusupload_fileobjwhen a workflow needs a real temporary file. - Store bucket and prefix configuration in environment variables instead of hardcoding them.
- Make sure the Lambda execution role includes the right
s3:PutObjectpermissions. - Add clear logging and exception handling so S3 failures are easy to diagnose.

