CodexBloom - Programming Q&A Platform

AWS Lambda not executing with proper IAM role permissions for S3 access in Node.js

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
aws lambda s3 iam node.js JavaScript

After trying multiple solutions online, I still can't figure this out... I'm having an scenario with my AWS Lambda function that's supposed to read files from an S3 bucket. The Lambda function is written in Node.js (version 14.x) and is triggered by an S3 event. I've ensured that the IAM role attached to the Lambda function has the necessary permissions, but I'm still getting an `Access Denied` behavior when it tries to access the bucket. The relevant part of my role policy is: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*" } ] } ``` I've tested the permissions using the AWS Policy Simulator and it shows that the Lambda role has access to the `s3:GetObject` action on the specified bucket. Here's the code I have in my Lambda function: ```javascript const AWS = require('aws-sdk'); const s3 = new AWS.S3(); exports.handler = async (event) => { const bucket = 'my-bucket'; const key = event.Records[0].s3.object.key; try { const data = await s3.getObject({ Bucket: bucket, Key: key }).promise(); console.log('File content:', data.Body.toString('utf-8')); } catch (err) { console.behavior('behavior getting object:', err); throw new behavior('behavior getting object from S3'); } }; ``` When I check the CloudWatch logs, the behavior I see is `AccessDenied: Access Denied` when the Lambda tries to execute `s3.getObject`. I've made sure that the bucket policy allows access from the Lambda's IAM role. The bucket policy looks like this: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:role/MyLambdaRole" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*" } ] } ``` I've also verified that the bucket name and key being passed are correct. I'm puzzled as to why the Lambda function isn't able to get the object from S3 despite having what seems to be the right permissions. Has anyone encountered a similar scenario or can provide insight on what might be going wrong? Am I missing something obvious? I'm working on a service that needs to handle this. I'd really appreciate any guidance on this.