Lambda function cannot access S3 bucket, even after granting IAM role/policy

0

I have followed the instructions for creating an AWS Lambda function and have created an IAM user role for an AWS Lambda function to access an S3 bucket. I have allowed both the putObject and getObject actions for the role, and specified which bucket I wanted Lambda to access within the creation page for the policy. Additionally, I unchecked the "Block all public access" button while creating my S3 bucket. However, whenever I try using boto3:

s3 = boto3.client('s3')
bucket_name = 'example_bucketname'
object_key = 'data.json' 

 try:
        response = s3.get_object(Bucket=bucket_name, Key=object_key)
        cached_data = response['Body'].read().decode('utf-8')
        return json.loads(cached_data)
    except s3.exceptions.NoSuchKey:
        return None

I receive an error stating "An error occurred (AccessDenied) when calling the GetObject operation: Access Denied" when testing my lambda function. Am I forgetting anything?

Any help will be much appreciated. Thank you! (Additionally, I have already looked at the guide posted by AWS OFFICIAL and I have also watched the YouTube video created by Francisco on the AWS OFFICIAL YouTube channel).

3 回答
1
已接受的回答

Something that will help you get more information is adding ListBucket permission to your function's IAM Role. I see you're trying to trap s3.exceptions.NoSuchKey but without ListBucket permission you'll never get this. Instead, if your object_key is wrong then you'll get "access denied".

Note that ListBucket applies to the bucket, not objects, so should be allowed for the "example_bucketname" resource, whereas GetObject & PutObject should be allowed for "example_bucketname/*".

If you're still having trouble please post your IAM policy here.

专家
已回答 2 个月前
profile picture
专家
已审核 2 个月前
1

The IAM Policy Simulator can be utilized to verify that your service roles possess the required permissions to execute the desired action.

IAM Policy Simulator

If the simulator encounters a failure when applying the service role to the resources, it indicates that your policy is improperly configured and requires correction.

profile picture
专家
已回答 2 个月前
0

Hello.

Are the S3 bucket name and object key correct?
Did you set the IAM policy for the correct IAM role?
You can check the Lambda IAM role as shown in the image below.
a

Also, since you are accessing with IAM, there is no need to uncheck "Block all public access".

profile picture
专家
已回答 2 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则