
⚡ Upload a File, Trigger a Function: Connecting S3 and Lambda
Yesterday we created a bucket. Today we make it do something. You'll connect Amazon S3 to AWS Lambda so that uploading a file automatically runs your code.
🧠 The Idea
In S3, an upload is an event. Lambda is event-driven, so it can run as soon as that event happens. No server sits waiting for files.
Upload file → S3 → Lambda → CloudWatch Logs
🛠️ Step 1: Create the Function
Open Lambda → Create function → Author from scratch.
Name it s3-upload-logger and choose Python as the runtime.
Click Create function.
Name it s3-upload-logger and choose Python as the runtime.
Click Create function.
💻 Step 2: Write the Code
This handler reads the bucket name and file name from the event and prints them:
1
2
3
4
5
def lambda_handler(event, context):
record = event["Records"][0]["s3"]
print("Bucket:", record["bucket"]["name"])
print("File:", record["object"]["key"])
return {"statusCode": 200}Click Deploy to save it.
🔗 Step 3: Add the S3 Trigger
In your function, click Add trigger and choose S3.
Select the bucket you created yesterday.
Set the event type to All object create events.
Tick the acknowledgement about recursive invocation, then click Add.
Select the bucket you created yesterday.
Set the event type to All object create events.
Tick the acknowledgement about recursive invocation, then click Add.
Lambda automatically gets the permission it needs to be invoked by S3.
📤 Step 4: Test It
Upload a file such as hello.txt to your bucket.
Open your function → Monitor → View CloudWatch logs.
Open the latest log stream. You'll see the bucket name and file name printed. 🎉
Open your function → Monitor → View CloudWatch logs.
Open the latest log stream. You'll see the bucket name and file name printed. 🎉
You never ran the function yourself. The upload did it.
⚠️ Avoid the Infinite Loop
Don't make this function write files back into the same bucket that triggers it. Each new file would trigger the function again, which creates an endless loop and a surprise bill. If you later process files, write the results to a separate bucket or a different prefix.
🔮 What's Next?
This worked because AWS services trust each other through permissions. Tomorrow I'll explore IAM: users, roles, and policies, and how they control who can do what in AWS.
💬 Your turn: Upload three files and check the logs. Does each upload create its own log entry?
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article